What is the difference between gets.chomp.to_i
and gets.chomp
in Ruby? What does it do and how does it work?
CodePudding user response:
gets
asks a user for some input and returns it exactly as it was entered. Notice that the returned value is a string and contains a newline at the end (since the user pressed the Enter
key to submit their response):
> gets
> 1 # user input
=> "1\n"
Adding chomp
removes the newline (technically, the record separator) from the input. Notice that "1"
is now missing the newline at the end, but is still a string:
> gets.chomp
> 1 # user input
=> "1"
Adding to_i
converts the input string into an integer. Notice that the return value is now an integer:
> gets.chomp.to_i
> 1 # user input
=> 1
Performing conversion with .to_i
only make sense for integer inputs, as other string values will return 0:
> gets.chomp.to_i
> foo # user input
=> 0
CodePudding user response:
gets
is used in scripts to retrieve user input. .chomp
is used to remove newlines and carriage returns. See here.
gets.chomp
does return a string -> to_i
converts the string to an integer.