Ruby&gt; <注入方法>累积数组中的字符串

时间:2016-02-14 21:14:08

标签: ruby rubygems

所有

Ruby的新手并且在玩耍。这是我的数组:

fruits = ["banana", "apple", "pear", "orange"]

我这样积累了:

longest_sentence = fruits.inject("banana") do |memo, fruit|
  if memo == fruits[0]
    puts "I like " + fruit + "s and "
  else
    puts fruit + "s and "
  end
end

正如所料,它给了我这个:

I like bananas and 
apples and 
pears and 
oranges and 
=> nil

以下是我的两个问题:

  1. 您如何将此代码压缩为一行(即无代码块)?
  2. 您如何将结果显示为单个字符串(即“我喜欢香蕉,苹果,梨和橙子以及没有尴尬的线条返回”)?
  3. 谢谢!

3 个答案:

答案 0 :(得分:2)

您传递给reduce的参数应该是您希望memo拥有的初始值。在这种情况下,看起来您希望它是"I like"。此外,请勿在块内执行putsreduce(如map等)用于“构建”对象。完成后,打印您构建的字符串:

sentence = fruits.inject("I like") do |memo, fruit|
  memo << " #{fruit}s and"
end

puts sentence
# => I like bananas and apples and pears and oranges and

答案 1 :(得分:0)

你不需要注入/减少。

fruits = ["banana", "apple", "pear", "orange"]
puts "I like " + fruits.map{|f| f + 's'}.join(' and ') 
# >> I like bananas and apples and pears and oranges

答案 2 :(得分:0)

puts "I like #{fruits.join('s and ')}s" 
  #-> I like bananas and apples and pears and oranges

puts "I like %ss" % fruits.join("s and ")