将Ruby数组解包为块

14
settings = [ ['127.0.0.1', 80], ['0.0.0.0', 443] ]

我该怎么做:

settings.each do |ip, port|  
    ...
end

不是:

settings.each do |config|  
    ip, port = *config
    ...
end
2个回答

9

你的第一个例子有效是因为Ruby可以解构块参数。有关Ruby中解构的更多信息,请参见此存档文章


3
您需要的方法是 Array#map
settings = [ ['127.0.0.1', 80], ['0.0.0.0', 443] ]
settings.map { |ip, port| puts "IP: #{ip} PORT: #{port}"  } 

这将返回

#// => IP: 127.0.0.1 PORT: 80<br/>
#// => IP: 0.0.0.0 PORT: 443

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接