使用过程和符号转换数组
Converting array using procs and symbols
我正在学习 Ruby 的 Codecademy 课程,我已经完成了 https://www.codecademy.com/en/courses/ruby-beginner-en-L3ZCI/1/6?curriculum_id=5059f8619189a5000201fbcb#
下面发布了将数字数组转换为字符串数组的正确代码(我不明白)。
numbers_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
strings_array = numbers_array.map(&:to_s)
我一直在浏览论坛和谷歌搜索,此时我仍然对这段代码到底发生了什么感到困惑。
我对:to_s
感到困惑,因为to_s
表示转换为字符串,而:
代表符号。 :to_s
是否将东西转换为符号或字符串?
我也对 &
感到困惑。我知道 &
符号使它后面的块成为 proc,但这里是符号的冒号和转换为字符串的方法,而不是 &
符号后面的块。
非常感谢任何帮助!
语法 &:to_s
是另一种构造块的方式,该块调用与数组中的每个项目匹配的方法的符号。在您的情况下,它与编写基本相同:
strings_array = numbers_array.map { |number| number.to_s }
这是另一个例子:
strings_array = numbers_array.map(&:to_f)
# Same as
strings_array = numbers_array.map { |number| number.to_f }
有关 &
符号的进一步解释,请查看如何定义接受块作为参数的方法。
def map(&block)
# ....
end
现在看看我们调用此方法的不同方式,它们都会产生相同的结果。
# Block using bracket notation
map { |n| n.to_i }
# Block using do ... end notition
map do |n|
n.to_i
end
# When using ampersand, ruby will try to treat the following as a
# proc and use to proc as the block for the method. If we pass a proc
# to it, then no problem.
p = proc { |n| n.to_i }
map(&p)
# When using ampersand with a symbol (or any other non-proc objects),
# ruby will try to call the to_proc method on the object and use that
# as a block. And in the scenario of passing a symbol, the Symbol
# object will return a proc that calls the method that matches the symbol.
:to_i.to_proc => #<Proc:...>
map(&:to_i)
我正在学习 Ruby 的 Codecademy 课程,我已经完成了 https://www.codecademy.com/en/courses/ruby-beginner-en-L3ZCI/1/6?curriculum_id=5059f8619189a5000201fbcb#
下面发布了将数字数组转换为字符串数组的正确代码(我不明白)。
numbers_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
strings_array = numbers_array.map(&:to_s)
我一直在浏览论坛和谷歌搜索,此时我仍然对这段代码到底发生了什么感到困惑。
我对:to_s
感到困惑,因为to_s
表示转换为字符串,而:
代表符号。 :to_s
是否将东西转换为符号或字符串?
我也对 &
感到困惑。我知道 &
符号使它后面的块成为 proc,但这里是符号的冒号和转换为字符串的方法,而不是 &
符号后面的块。
非常感谢任何帮助!
语法 &:to_s
是另一种构造块的方式,该块调用与数组中的每个项目匹配的方法的符号。在您的情况下,它与编写基本相同:
strings_array = numbers_array.map { |number| number.to_s }
这是另一个例子:
strings_array = numbers_array.map(&:to_f)
# Same as
strings_array = numbers_array.map { |number| number.to_f }
有关 &
符号的进一步解释,请查看如何定义接受块作为参数的方法。
def map(&block)
# ....
end
现在看看我们调用此方法的不同方式,它们都会产生相同的结果。
# Block using bracket notation
map { |n| n.to_i }
# Block using do ... end notition
map do |n|
n.to_i
end
# When using ampersand, ruby will try to treat the following as a
# proc and use to proc as the block for the method. If we pass a proc
# to it, then no problem.
p = proc { |n| n.to_i }
map(&p)
# When using ampersand with a symbol (or any other non-proc objects),
# ruby will try to call the to_proc method on the object and use that
# as a block. And in the scenario of passing a symbol, the Symbol
# object will return a proc that calls the method that matches the symbol.
:to_i.to_proc => #<Proc:...>
map(&:to_i)