【发布时间】:2023-04-04 03:39:01
【问题描述】:
我需要帮助找出为什么 map 和以下代码中的 each 之间存在差异。
j = "This is an awesome string"
j.split('').map do |char|
char.next! if char =~ /[A-Za-z]/
end
这会返回:
["U", "i", "j", "t", nil, "j", "t", nil, "b", "o", nil, "b", "x", "f", "t", "p", "n", "f", nil, "t", "u", "s", "j", "o", "h"]
但是
j.split('').each do |char|
char.next! if char =~ /[A-Za-z]/
返回:
["U", "i", "j", "t", " ", "j", "t", " ", "b", "o", " ", "b", "x", "f", "t", "p", "n", "f", " ", "t", "u", "s", "j", "o", "h"]
为什么从map 更改为each 会去掉nil?
【问题讨论】:
-
和往常一样,在 ruby 中有一个单行符:
"This is an awesome string".gsub(/[A-z]/) { |c| c.next }与问题不严格相关,但仍然值得了解(我认为,无论如何)。 -
@asQuirreL 在你的路上..
"This is an awesome string".enum_for(:gsub, /[a-z]/i).map(&:next)...希望你会喜欢。它实际上是#map,它将在迭代期间向您展示它所做的事情。 :-) -
同样,有
This is an awesome string".gsub(/[A-z]/, &:next)(您的解决方案的问题是它实际上删除了非字母字符,而不是忽略它们)。 -
@asQuirreL 这是#gsub .. 不是#gsub! ..别担心。 :-)