1

I am working with Ruby. I need to grab each key/value and put it into a string.

So far I have:

values = ['first' => '1', 'second' => '2']
  @thelink = values.collect do | key, value |
  "#{key}=#{value}&"
  end

When I print @thelink I see:

first1second2=&

But Really what I want is

first=1&second=2

Could anybody help/explain please?

0

2 Answers 2

2

There is something subtle you are missing here {} vs [].

See the below taken from IRB tests:

irb(main):002:0> {'first' => 1, 'second' => 2}
=> {"second"=>2, "first"=>1}

irb(main):003:0>  ['first' => 1, 'second' => 2]
=> [{"second"=>2, "first"=>1}]

irb(main):004:0> {'first' => 1, 'second' => 2}.class
=> Hash

irb(main):005:0>  ['first' => 1, 'second' => 2].class
=> Array

Similar to this:

irb(main):006:0> {'first' => 1, 'second' => 2}.collect { |key,value| puts "#{key}:#{value}" }
second:2
first:1
=> [nil, nil]

irb(main):007:0> ['first' => 1, 'second' => 2].collect { |key,value| puts "#{key}:#{value}" }
second2first1:
=> [nil]

The array has a single element (a hash) that, as a string, is everything concatenated. This is the important thing to note here.
On the other hand, the hash iterates by handing you the key/value pairs that you are expecting.

Hope that helps.

0
1

I think your code has a typo (a hash is delimited by {} not by []). Try this

values = {'first' => '1', 'second' => '2'}
r = values.map{|k,v| "#{k}=#{v}"}.join('&')
puts r
#shows: first=1&second=2
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.