简体   繁体   中英

Difference between gets.chomp.to_i and gets.chomp in Ruby

What is the difference between gets.chomp.to_i and gets.chomp in Ruby? What does it do and how does it work?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM