Ruby: What's the difference between STDIN.gets() and gets.chomp()?

What's the difference between STDIN.gets() and gets.chomp() in Ruby? Aren't they both retrieving raw input from the user?

side question: If I want to convert their input into an integer, do I do

myNumb = Integer(STDIN.gets())

and

myNumb = Integer(gets.chomp()) 

Answers


Easiest way to do what you describe here is Integer(gets), since Integer() ignores the trailing newline, so chomp is unnecessary. There's also no need explicitly specify STDIN as the receiver, as that's what Kernel#gets will do if there are no arguments to the script.


gets is actually Kernel#gets. It reads from files passed as arguments or, if no arguments are present, reads from standard input. If you want to read only from standard input, then you should be more explicit about it.

STDIN.gets
$stdin.gets

As for the conversion, I normally use String#to_i. It handles newlines just fine.


Need Your Help

Get Place categories from DBpedia using SPARQL

category sparql dbpedia

The following code queries DBpedia for places within a bounded geographic area and returns the name, lat, and long of the place. I'd also like the query to return the category of the place--e.g., p...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.