Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby unpack array to block

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

How can I do:

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

Instead of:

settings.each do |config|  
    ip, port = *config
    ...
end
like image 441
Pawel Furmaniak Avatar asked Mar 24 '13 11:03

Pawel Furmaniak


2 Answers

Your first example works because Ruby will destructure block arguments. See this article for more information on destructuring in ruby.

like image 62
Sahil Muthoo Avatar answered Oct 14 '22 03:10

Sahil Muthoo


The method you're looking for is Array#map

settings = [ ['127.0.0.1', 80], ['0.0.0.0', 443] ]
settings.map { |ip, port| puts "IP: #{ip} PORT: #{port}"  } 

which will return
#// => IP: 127.0.0.1 PORT: 80
#// => IP: 0.0.0.0 PORT: 443

like image 23
JtoTheGoGo Avatar answered Oct 14 '22 04:10

JtoTheGoGo