什么是Ruby相当于字符串的map()?

EMB*_*LEM 15 ruby string-split

如果你想拆分以空格分隔的单词列表,你可以使用

def words(text)
    return text.split.map{|word| word.downcase}
end
Run Code Online (Sandbox Code Playgroud)

类似于Python的列表理解:

words("get out of here")
Run Code Online (Sandbox Code Playgroud)

返回["get", "out", "of", "here"].如何将块应用于字符串中的每个字符?

Jer*_*ten 24

用途String#chars:

irb> "asdf".chars.map { |ch| ch.upcase }
  => ["A", "S", "D", "F"]
Run Code Online (Sandbox Code Playgroud)

  • 我唯一能想到的是"asdf".gsub(/./){| ch | ch.upcase}`,但它有点难看/混乱.`"asdf".chars.map(&:upcase).join`是更好的IMO. (3认同)

Car*_*and 7

你在找这样的东西吗?

class String
  def map
    size.times.with_object('') {|i,s| s << yield(self[i])}
  end
end

"ABC".map {|c| c.downcase}       #=> "abc" 
"ABC".map(&:downcase)            #=> "abc"
"abcdef".map {|c| (c.ord+1).chr} #=> "bcdefg"
"abcdef".map {|c| c*3}           #=> "aaabbbcccdddeeefff"
Run Code Online (Sandbox Code Playgroud)