I want to write a simple A+B program in ruby, but I have no idea how to work with the console.
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?
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
you can also pass the parameters through the command line. Command line arguments are stores in the array ARGV. so ARGV[0] is the first number and ARGV[1] the second number
#!/usr/bin/ruby
first_number = ARGV[0].to_i
second_number = ARGV[1].to_i
puts first_number + second_number
and you call it like this
% ./plus.rb 5 6
==> 11
There are many ways to take input from the users. I personally like using the method gets. When you use gets, it gets the string that you typed, and that includes the ENTER key that you pressed to end your input.
name = gets
"mukesh\n"
You can see this in irb; type this and you will see the \n, which is the “newline” character that the ENTER key produces: Type
name = gets
you will see somethings like"mukesh\n"
You can get rid of pesky newline character using chomp method.
The chomp method gives you back the string, but without the terminating newline. Beautiful chomp method life saviour.
name = gets.chomp
"mukesh"
You can also use terminal to read the input. ARGV is a constant defined in the Object class. It is an instance of the Array class and has access to all the array methods. Since it’s an array, even though it’s a constant, its elements can be modified and cleared with no trouble. By default, Ruby captures all the command line arguments passed to a Ruby program (split by spaces) when the command-line binary is invoked and stores them as strings in the ARGV array.
When written inside your Ruby program, ARGV will take take a command line command that looks like this:
test.rb hi my name is mukesh
and create an array that looks like this:
["hi", "my", "name", "is", "mukesh"]
But, if I want to passed limited input then we can use something like this.
test.rb 12 23
and use those input like this in your program:
a = ARGV[0]
b = ARGV[1]
if you want to hold the arguments from Terminal, try the following code:
A = ARGV[0].to_i
B = ARGV[1].to_i
puts "#{A} + #{B} = #{A + B}"
If you want to make interactive console:
#!/usr/bin/env ruby
require "readline"
addends = []
while addend_string = Readline.readline("> ", true)
addends << addend_string.to_i
puts "#{addends.join(' + ')} = #{addends.sum}"
end
Usage (assuming you put above snippet into summator
file in current directory):
chmod +x summator
./summator
> 1
1 = 1
> 2
1 + 2 = 3
Use Ctrl + D
to exit