在 ruby 中编写此 .map() 的更好方法?
Nicer way to write this .map() in ruby?
我有一个如下所示的数组:[[3, 1], 4, [3, 3, 4], 4, :sync, 1, 2]
我想通过数组映射,并且...
- 如果该项是整数,请将其替换为其他值
- 如果项目是一个数组,只替换索引 0 的项目,return 数组
这是我目前拥有的,但它非常难看。有没有更好的写法?
也许我能以某种方式使用 #tap
?
work.map! do |w|
if w.is_a? Array
w[0] = console.button_map[w[0]] || w[0]
w
else
console.button_map[w] || w
end
end
我确定了这个,不确定它是否可以更清洁:
work.map! do |w|
if w.is_a? Array
w.tap{|x| x[0] = console.button_map[x[0]] || x[0] }
else
console.button_map[w] || w
end
end
我会使用 Array()
来规范化输入,然后只剩下一个案例:
work.map! do |w|
element = Array(w).first
console.button_map[element] || element
end
work = [[3, 1], 4, [3, 3, 4], 4, :sync, 1, 2, [5]]
work.map! do |w|
val = my_method [*w].first
case w
when Array then [val, *w[1..-1]]
else val
end
end
def my_method(n)
case n
when Fixnum then n+4
else n.to_s
end
end
work
#=> [[7, 1], 8, [7, 3, 4], 8, "sync", 5, 6, [9]]
注:
[*[1,2]] #=> [1,2]
[*3] #=> [3]
我有一个如下所示的数组:[[3, 1], 4, [3, 3, 4], 4, :sync, 1, 2]
我想通过数组映射,并且...
- 如果该项是整数,请将其替换为其他值
- 如果项目是一个数组,只替换索引 0 的项目,return 数组
这是我目前拥有的,但它非常难看。有没有更好的写法?
也许我能以某种方式使用 #tap
?
work.map! do |w|
if w.is_a? Array
w[0] = console.button_map[w[0]] || w[0]
w
else
console.button_map[w] || w
end
end
我确定了这个,不确定它是否可以更清洁:
work.map! do |w|
if w.is_a? Array
w.tap{|x| x[0] = console.button_map[x[0]] || x[0] }
else
console.button_map[w] || w
end
end
我会使用 Array()
来规范化输入,然后只剩下一个案例:
work.map! do |w|
element = Array(w).first
console.button_map[element] || element
end
work = [[3, 1], 4, [3, 3, 4], 4, :sync, 1, 2, [5]]
work.map! do |w|
val = my_method [*w].first
case w
when Array then [val, *w[1..-1]]
else val
end
end
def my_method(n)
case n
when Fixnum then n+4
else n.to_s
end
end
work
#=> [[7, 1], 8, [7, 3, 4], 8, "sync", 5, 6, [9]]
注:
[*[1,2]] #=> [1,2]
[*3] #=> [3]