英文:
Mapping and choosing from an array of arrays(which is just a pair of elements). Ruby
问题
我有这个数组:
`[["A", 0], ["B", 0], ["b", 0], ["F", 1], ["G", 2], ["g", 3], ["C", 0]]`
我想从这些键值对中选择是否为0,并创建一个新的数组,结果如下:
`["A","B","b",1,2,3,"C"]`
我尝试使用以下代码:
arr.each do |a|
if a.last == 0
a.first
else
a.last
end
end
但它返回原始数组。
英文:
I have this array:
[["A", 0], ["B", 0], ["b", 0], ["F", 1], ["G", 2], ["g", 3], ["C", 0]]
and I want to choose from the pair if it's 0 or not and create a new array that results into this
["A","B","b",1,2,3,"C"]
I tried using
arr.each do |a|
if a.last == 0
a.first
else
a.last
end
end
but it returns the original array.
答案1
得分: 1
你已经非常接近了。只需使用 map
而不是 each
。each
只是遍历调用它的 Enumerable
,然后返回原始对象。而 map
也会遍历 Enumerable
,但返回的是这些迭代的结果值的数组。
要传递不同的值作为迭代块的结果值,而不是其最后一个命令的返回值,请使用 next
。调用 next value
将停止处理当前循环,并以 value
作为其结果值。
你的可工作的代码如下:
arr = [["A", 0], ["B", 0], ["b", 0], ["F", 1], ["G", 2], ["g", 3], ["C", 0]]
new_arr = arr.map do |a|
if a.last == 0
a.first
else
a.last
end
end
# => ["A", "B", "b", 1, 2, 3, "C"]
使用 next
的代码示例如下:
arr = [["A", 0], ["B", 0], ["b", 0], ["F", 1], ["G", 2], ["g", 3], ["C", 0]]
new_arr = arr.map do |a|
next a.first if a.last == 0
a.last
end
# => ["A", "B", "b", 1, 2, 3, "C"]
英文:
You are really close. Just use map
instead of each
. each
just loops through the Enumerable
it is called on and returns the original object. map
also loops through the Enumerable
but returns an Array
of result values of those iterations.
To pass a different value as a result value of an iteration block than a return value of its last command use next
. Calling next value
will stop processing the current loop with value
as its result.
Your working code is:
arr = [["A", 0], ["B", 0], ["b", 0], ["F", 1], ["G", 2], ["g", 3], ["C", 0]]
new_arr = arr.map do |a|
if a.last == 0
a.first
else
a.last
end
end
#=> ["A", "B", "b", 1, 2, 3, "C"]
A code example using next
arr = [["A", 0], ["B", 0], ["b", 0], ["F", 1], ["G", 2], ["g", 3], ["C", 0]]
new_arr = arr.map do |a|
next a.first if a.last == 0
a.last
end
#=> ["A", "B", "b", 1, 2, 3, "C"]
答案2
得分: 0
替代#each
或甚至map
,你也可以使用#each_with_object
,你可以传入你选择的任何对象,但听起来你想要一个数组,这里是一个例子:
new_array = input.each_with_object([]) do |a, arr|
# 传递给块的第二个值 `arr` 是一个空数组 `[]`
arr << if a.last.zero?
a.first
else
a.last
end
end
# => ["A", "B", "b", 1, 2, 3, "C"]
英文:
instead of #each or even map you could also use #each_with_object, you could pass in any object of your choice but sounds like you want an array here is an example
new_array = input.each_with_object([]) do |a, arr|
# the second value `arr` passed to the block is the []
arr << if a.last.zero?
a.first
else
a.last
end
end
#=> ["A", "B", "b", 1, 2, 3, "C"]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论