Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read input from console in Ruby?

Tags:

ruby

console

I want to write a simple A+B program in ruby, but I have no idea how to work with the console.

like image 253
Sergey Avatar asked Oct 04 '22 03:10

Sergey


People also ask

How do I get input in Ruby?

In Ruby, user input is made possible by the #gets method. During the executing of a Ruby program, when a line with the #gets method is read, the terminal is primed for input from the user. The input is returned as a string type after the #gets method is finished. puts "My name is #{name}!"

What is gets chomp in Ruby?

chomp! is a String class method in Ruby which is used to returns new String with the given record separator removed from the end of str (if present). chomp method will also removes carriage return characters (that is it will remove \n, \r, and \r\n) if $/ has not been changed from the default Ruby record separator, t.

How do you print text in Ruby?

To display a string in your program, you can use the print method: print "Let's print out this string." The print method displays the string exactly as written. print 'This is the first string.

How to do input and output in Ruby?

Several classes in Ruby have methods for doing input & output operations. For example Kernel, IO , Dir or File . Some of the examples use this file. Ruby has several methods for printing output on the console.

How to print output on the console in Ruby?

Ruby has several methods for printing output on the console. These methods are part of the Kernel module. Methods of the Kernel are available to all objects in Ruby. The print and puts methods produce textual output on the console. The difference between the two is that the latter adds a new line character.

How to read input from console in Java?

Ways to read input from console in Java. In Java, there are three different ways for reading input from the user in the command line environment(console). 1.Using Buffered Reader Class. This is the Java classical method to take input, Introduced in JDK1.0.

How do you read data from a file in Ruby?

The read method reads data from the standard input until it reaches the end of the file. EOF is produced by pressing Ctrl + D on Unix and Ctrl + Z on Windows. $./reading.rb Ruby language Ruby language When we launch a program without a parameter, the script reads data from the user.


1 Answers

Are you talking about gets?

puts "Enter A"
a = gets.chomp
puts "Enter B"
b = gets.chomp
c = a.to_i + b.to_i
puts c

Something like that?

Update

Kernel.gets tries to read the params found in ARGV and only asks to console if not ARGV found. To force to read from console even if ARGV is not empty use STDIN.gets

like image 250
siame Avatar answered Oct 06 '22 17:10

siame