所有
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
以下是我的两个问题:
谢谢!
答案 0 :(得分:2)
您传递给reduce
的参数应该是您希望memo
拥有的初始值。在这种情况下,看起来您希望它是"I like"
。此外,请勿在块内执行puts
。 reduce
(如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 ")