只是想知道是否还有来自
的数组合并元素的其他替代方法[[" time"," Oct-1-2016"],[" message"," test message"], ["主持人"," localhost"]]
到
[" time = Oct-1-2016"," message = test message"," host = localhost"]
我已经把它钉在array.map {|k,v| "#{k}=#{v}"}
上,只是想知道是否有其他方法可以在不使用地图功能的情况下实现上述目标?谢谢你!
答案 0 :(得分:2)
假设你的数组是a
。然后尝试这个解决方案:
[1] pry(main)> a = [ ["time","Oct-1-2016"], ["message","test message"], ["host","localhost"] ]
=> [["time", "Oct-1-2016"], ["message", "test message"], ["host", "localhost"]]
[2] pry(main)> a.map{|k, v| "#{k}=#{v}"}
=> ["time=Oct-1-2016", "message=test message", "host=localhost"]
嗯,我不知道为什么map
不适合你,但这是一个inject
的例子:
[40] pry(main)> a.inject(Array.new){|acc, el| acc << el.join("="); acc}
=> ["time=Oct-1-2016", "message=test message", "host=localhost"]
答案 1 :(得分:1)
这是使用Enumerator
内部的无限循环并使用cycle
方法的一种方法。然后使用enum.take arr.size
获取数组中的所有新元素。
arr = [ ["time","Oct-1-2016"], ["message","test message"], ["host","localhost"] ]
ar = arr.cycle
enum = Enumerator.new do |y|
loop do
y << ar.next.join('=')
end
end
enum.take arr.size
#=> ["time=Oct-1-2016", "message=test message", "host=localhost"]