Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding map in Ruby

I'm pretty new to Ruby and am trying to understand an example of the map method that I came across:

{:a => "foo", :b => "bar"}.map{|a, b| "#{a}=#{b}"}.join('&')

which returns:

=> "a=foo&b=bar"

I don't understand how the

b=bar

is returned. The string interpolation is what is confusing me as it seems it would return something like:

=> "a=foo&bbar"
like image 816
mxmxx Avatar asked Feb 03 '26 00:02

mxmxx


1 Answers

> {:a => "foo", :b => "bar"}.map{|key, value| "#{key}=#{value}"}
#=> ["a=foo", "b=bar"]

map method will fetch each element of hash as key and value pair

"#{key}=#{value}" is a String Interpolation which adds = between your key and value

Using this syntax everything between the opening #{ and closing } bits is evaluated as Ruby code, and the result of this evaluation will be embedded into the string surrounding it.

Array#join will returns a string created by converting each element of the array to a string, separated by the given separator.

so here in your case:

> ["a=foo", "b=bar"].join('&')
#=> "a=foo&b=bar" 

In Rails you can convert hash to query params using Hash#to_query method, which will return the same result.

 > {:a => "foo", :b => "bar"}.to_query
 #=> "a=foo&b=bar"
like image 121
Gagan Gami Avatar answered Feb 06 '26 00:02

Gagan Gami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!