Reputation: 1417
Below is the code which I tried in ruby console. Can anyone tell me why the output is different in this two cases for the same input.
2.1.4 :014 > def a_method
2.1.4 :015?> puts "enter"
2.1.4 :016?> a = gets.chomp
2.1.4 :018?> puts a
2.1.4 :019?> puts a.to_i
2.1.4 :020?> end
=> :a_method
2.1.4 :021 > a_method
enter
"12"
"12"
0 (output of a.to_i)
=> nil
2.1.4 :022 > "12".to_i
=> 12
Here I'm just converting a string number into integer by reading from console using gets, which is giving 0 as output. If I do the same by just giving "12".to_i then I'm getting proper output. Why is that?
Upvotes: 0
Views: 54
Reputation: 3053
This output might help explain the issue:
2.1.1 :001 > def a_method
2.1.1 :002?> puts "enter"
2.1.1 :003?> a = gets.chomp
2.1.1 :004?> puts a.class.name
2.1.1 :005?> puts a
2.1.1 :006?> puts a.to_i
2.1.1 :007?> end
=> :a_method
2.1.1 :008 > a_method
enter
"12"
String
"12"
0
=> nil
2.1.1 :009 > a_method
enter
12
String
12
12
=> nil
gets
is short for get string, so if you enter 12
it turns it into "12"
. As Jiří Pospíšil pointed out, if you enter "12"
, it turns it into "\"12\""
, which to_i
is unable to understand.
Upvotes: 1
Reputation: 14412
Inspect the intermediate variable a
when entering "12"
(with quotes)
a = gets.chomp
# a => "\"12\""
a.to_i # => 0
"\"12\"".to_i # => 0
If you want to enter the actual number, not a string representation of it, do not use the quotes.
Upvotes: 2