Prev: Exception change with net/http in Ruby 187 PL 248/9
Next: Is it possible to run rb file on safari browser in windowsXP
From: Jesús Gabriel y Galán on 18 Feb 2010 03:20 On Thu, Feb 18, 2010 at 4:17 AM, Spencer Spence <spencaatee(a)live.com> wrote: > ah thank you, not totally sure why I made number a class variable. So > that's figured out but when i run it, if i type 2 and 2, it prints 2 2 > instead of adding them like integers it adds them like strings. That's because gets returns a string, and the + method of string concatenates them: irb(main):001:0> "2" + "2" => "22" irb(main):002:0> 2 + 2 => 4 irb(main):003:0> number = gets.to_i 2 => 2 irb(main):004:0> number2 = gets.to_i 2 => 2 irb(main):005:0> number + number2 => 4 To convert a string to an integer check the to_i method: http://ruby-doc.org/core/classes/String.html#M000787 Hope this helps, Jesus. |