ACC
ACC

Reputation: 2560

Inconsistent printing with Ruby

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?

Upvotes: 0

Views: 52

Answers (3)

knut
knut

Reputation: 27875

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.)

Upvotes: 5

jblack
jblack

Reputation: 93

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

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

Upvotes: 4

Nir Alfasi
Nir Alfasi

Reputation: 53535

Try:

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

Upvotes: 1

Related Questions