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

时间:2022-06-24 20:20:48

I have below code in helper:

我在helper中有以下代码:

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

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

It works fine, but in the first version I tried each instead of map and it didn't work. Could anyone explain me why? (each version generated just <ul>onetwothree</ul>)

它工作正常,但在第一个版本我尝试了每个而不是地图,它没有工作。谁能解释我为什么? (每个版本只生成

    onetwothree )

1 个解决方案

#1


3  

This is because Array#each returns the receiver itself on which it was called.But Array#map returns a new array containing the values returned by the block.

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

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

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

#1


3  

This is because Array#each returns the receiver itself on which it was called.But Array#map returns a new array containing the values returned by the block.

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

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

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