Ruby数组元素合并

时间:2016-09-23 02:33:37

标签: arrays ruby ruby-on-rails-3

只是想知道是否还有来自

的数组合并元素的其他替代方法
  

[[" time"," Oct-1-2016"],[" message"," test message"],   ["主持人"," localhost"]]

  

[" time = Oct-1-2016"," message = test message"," host = localhost"]

我已经把它钉在array.map {|k,v| "#{k}=#{v}"}上,只是想知道是否有其他方法可以在不使用地图功能的情况下实现上述目标?谢谢你!

2 个答案:

答案 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"]