Why does doubling just puts the number twice?

Viewed 62

So I'm real new to Ruby and I'm not sure exactly how things work. I've been working through the Codecademy and experimenting with some things. Anyway, I want to use a yield statement to double a number I feed into the terminal. Here's what I have

 def double(i)
  puts "Type a number!"
  yield(i)
  puts "Look at that! It's doubled!"
end

double(gets.chomp) {|i| puts i*2}

Weirdly, rather than doubling it, this is returning the number twice, i.e. if I input 3, I get 33, not 6. When I replace the gets.chomp with an integer, it doubles it properly though, so Somehow my gets.chomp must be flawed, but I have no idea how. Any advice would help immensely. Thanks!

1 Answers

Try using the .to_i function since gets.chomp returns text.

 def double(i)
  i = i.to_i
  puts "Type a number!"
  yield(i)
  puts "Look at that! It's doubled!"
end

double(gets.chomp) {|i| puts i*2}

tried and tested in codecademy

Related