问题 Ruby解压缩数组来阻止


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

6616
2018-03-24 11:46


起源

去做就对了。它会像你一样工作。 - sawa


答案:


你的第一个例子是有效的,因为Ruby将解构块参数。看到这个 文章 有关红宝石解构的更多信息。


8
2018-03-24 12:21





您正在寻找的方法是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端口:80
    #// => IP:0.0.0.0 PORT:443


2
2018-03-25 06:09