Read input from console in Ruby?
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
Taking input from user in console in ruby
You probably have a newline in your input you haven't stripped. When processing data from files, be sure to chomp
any input values. Even better is to call strip
which will remove leading and trailing spaces.
gets.chomp.split(',')
Whenever trying to do diagnostics, it's important to show "invisible" characters:
puts code_2.inspect
# "TYP\n"
This would probably have exposed the issue sooner. inspect
can be misleading, though, on custom classes that have their own customized emitter. It can't always be trusted, but it's usually a good place to start.
How can I get user input from command line with this program?
ARGV
is an array. You have to get its first element.
print ARGV # An array
x = ARGV[0]
print x
With ruby filename.rb 123
, ARGV
is ["123"]
and x
is "123"
.
make ruby script in console keep accepting input until you're done
Yes,, you can try as something like below using while
keyword :
puts "Give your inputs"
while (a = gets.chomp) != 'exit'
puts a
end
# or use until as below
until (a = gets.chomp) =~ /(?:ex|qu)it/i
puts a
end
While you will enter the string 'Exit'
/'exit'
/'Quit'
/'quit'
from the command prompt, your while loop will be stopped, Otherwise you will be keep prompting for the next input.
Output to console while preserving user input in ruby
The two important parts of my proposal are:
1. system("stty raw -echo") # to instantly get any typed character in combination with
2. using STDIN.getc with a string-var serving as an input-buffer to reprint the user input.
Pressing 9 (& boolean variable incoming_message) is used for ultra-simple simulation for your server-messages.
(Being more realistic would bloat the example without adding much, since you have to adapt the idea for your scenario anyway.)
Press x for exit.
Sample output:
$ ruby simultaneous_input_and_output.rb
Hello World!9
The incoming message is: true
Hello World!9x
You entered:
Hello World!9x
End!
#!/usr/bin/ruby
$input_buffer = "";
incoming_message = false
begin
system("stty raw -echo")
begin
str = STDIN.getc
print str.chr
$input_buffer = $input_buffer + str.chr
if str.chr == '9'
incoming_message = true
end
if incoming_message
puts "\nThe incoming message is: " + incoming_message.to_s
print $input_buffer
incoming_message = false
end
end while (str.chr != 'x')
ensure
system("stty -raw echo")
end
puts "\n\nYou entered:"
puts $input_buffer
puts "End!"
P.S.:
for system("stty raw -echo") see (User Jay)
How to get a single character without pressing enter?
How do I read an input file in ruby using in command line?
I'm assuming the content of the input files will be different and you will have some logic to determine that. You can actually just read that file input as if it was entered as text by the user and do whatever you need to do with it.
Example:
test.rb
puts gets.chomp
testfile
test
Terminal
$ ruby test.rb < testfile
$ test
Program to take input from command line into an array and find the biggest among them
How about capturing the array in one line?
#!/usr/bin/ruby
puts "Enter a list of numbers"
list = gets # Input something like "1 2 3 4" or "3, 5, 6, 1"
max = list.split.map(&:to_i).max
puts "The largest number is: #{max}"
Testing program that runs with user input from the console
As demonstrated in this answer, you can override getvalue
to feed in the user input.
Here is complete code that works without actually using gets
. I had to add couple of missing methods - validate_floor_number
and final_destination
:
require 'minitest/autorun'
class Elevator
attr_accessor :current_floor
def initialize
@current_floor = 0
@requested_floor = 0
#@last_floor = false
end
def get_value
gets.chomp
end
def validate_floor_number(v)
v.to_i rescue false
end
def arrival
print "Enter floor number: "
@requested_floor = get_value
# only proceed if user entered an integer
if validate_floor_number(@requested_floor)
@requested_floor = @requested_floor.to_i
move
else
arrival
end
end
def move
msg = ""
@current_floor < @requested_floor ? msg = "Going Up!" : msg = "Going Down"
puts msg
@current_floor = @requested_floor
next_move
end
def final_destination
puts "Reached your floor"
end
def next_move
puts "Do you want to go to another floor? Y/N"
another_floor = (get_value).upcase
another_floor == 'N' ? final_destination : arrival
end
end
describe "checks that the elevator can change directions" do
before do
class Elevator
@@moves = [3, 'Y', 5, 'Y', 2, 'Y', 7, 'N'].each
def get_value; @@moves.next end
end
end
it "should stop on floor 7" do
e = Elevator.new
e.arrival
assert_equal(e.current_floor, 7)
end
end
Output of above program:
Run options: --seed 2561
# Running:
Enter floor number: Going Up!
Do you want to go to another floor? Y/N
Enter floor number: Going Up!
Do you want to go to another floor? Y/N
Enter floor number: Going Down
Do you want to go to another floor? Y/N
Enter floor number: Going Up!
Do you want to go to another floor? Y/N
Reached your floor
.
Finished in 0.001334s, 749.4982 runs/s, 749.4982 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
[Finished in 0.3s]
Related Topics
Advantage of Tap Method in Ruby
How to Create a Copy of Some Columns of a CSV File in Ruby with Different Data in One Column
Disable a Group of Tests in Rspec
Break and Return in Ruby, How to Use Them
How to Set Ruby's Load Path Externally
Rails - Invalid Authenticity Token After Deploy
How to Manage Multiple Gemsets and Ruby Versions with Rvm
Purpose of & (Ampersand) in Ruby for Procs and Calling Methods
How to Initialize an Array Inside a Hash in Ruby
Ruby: How to Load a File into Interactive Ruby Console (Irb)
Ruby Convert Array into Function Arguments
Why Do I Need to Work Harder to Make My Rails Application Fit into a Restful Architecture
Rails If Object.Nil? Then Magic '' in Views
Rails-Like Database Migrations
How to Take Screenshots of Web Pages Using Ruby and a Unix Server