content_tag with array and ul,li tags - map vs each

时间:2013-10-07 14:44:17

标签: ruby-on-rails ruby

我在helper中有以下代码:

arr = ['one', 'two', 'three']

errors = content_tag :ul do
  arr.map do |msg|
    content_tag :li, msg
  end.join.html_safe
end

它工作正常,但在第一个版本中,我尝试了each而不是map,但它无效。谁能解释我为什么? (仅each生成的<ul>onetwothree</ul>版本)

1 个答案:

答案 0 :(得分:3)

这是因为Array#each返回调用它的接收器本身。但是Array#map返回一个包含块返回值的新数组。

arr = ['one', 'two', 'three']

arr.each {|i|  i + 'weak' }.join(" ") # "one two three"
arr.map {|i|  i + 'weak' }.join(" ") #"oneweak twoweak threeweak"