0

I am trying to print a ruby hash:

opts = {
  'one' => '1',
  'two' => '1',
  'three' => '0'
}

I want the output to be

one=1
two=1
three=0

This works fine with this code on one machine which runs ruby 1.8.7

print opts.map{|k,v| k + '=' + v + "\n"}.to_s

But on a different machine which runs ruby 1.9, it prints

["one=1\n", "two=1\n", "three=0\n"]

What is going wrong?

ACC
  • 2,488
  • 6
  • 35
  • 61

3 Answers3

5

Try

print opts.map{|k,v| k + '=' + v + "\n"}.join

The explanation is easy: With ruby 1.9 Array.to_s changed its behaviour.

An alternative:

puts opts.map{|k,v| k + '=' + v }.join("\n")

or

puts opts.map{|k,v| "#{k}=#{v}" }.join("\n")

I would prefer:

opts.each{|k,v| puts "#{k}=#{v}" }

And another version, but with another look:

opts.each{|k,v| puts "%-10s= %s" % [k,v]}

The result is:

one       = 1
two       = 1
three     = 0

(But the keys should be not longer then the length in %-10s.)

Community
  • 1
  • 1
knut
  • 27,320
  • 6
  • 84
  • 112
4

It's working as expected. Give this a try:

a={:one=>1, :two=>2, :three=>3}
a.each {|k,v| puts "#{k}=>#{v}" }
jblack
  • 93
  • 5
1

Try:

res = ""
opts.map{|k,v| res += k + '=' + v + "\n"}
puts res
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129