Using 'gets' sends uknown data

I can’t figure out where the input comes from in the following code:

def check_input
puts “In which city do you stay?”
city = gets.chomp
puts "The city is " + city

When calling in a separate way (from inside the same file):, nil).check_input

it works as needed.

When I tried to call the same from another place

$LOAD_PATH.unshift File.expand_path(’…/…/lib’, FILE)
require ‘laby’, nil).check_input

I’m getting the below output:

In which city do you stay?
The city is ################################

and the program exits. Really weird…
When I quit the terminal and reopen it, it works.
Is it due to a previous file reading that I commented just to execute
above code ?
Any idea? Thank you.

Try STDIN.gets.chomp and tell us if the input is the same.

Returns (and assigns to $_) the next line from the list of files in
ARGV (or $*), or from standard input if no files are present on the
command line.

Perhaps it’s getting its input from a file in ARGV (command line

Abinoam Jr.

On Wed, Jan 29, 2014 at 4:58 PM, Serguei C. [email protected]

file_name = ‘data.txt’

there was no problem.

After changing it to:

file_name = ARGV.pop

In any case, if you want to support passing arguments to the scripts
and also reading from stdin, you can avoid using the Kernel method,
and as Abinoam suggested, use $stdin.gets. This way you don’t have to
do any workarounds on ARGV to have gets work on stdin.


ok, thanks, i’ll take a look at that.

Fixed it.
Later I passed a file name as follows in the start up file:

file_name = ARGV.first

in the terminal I just taped in:

ruby bin/my_ruby_file.rb data.txt

When hard coding the file name as folllows:

file_name = ‘data.txt’

there was no problem.

After changing it to:

file_name = ARGV.pop

it worked with some modifications in the method reading the keyboard

def query_next_direction
input = gets.chomp
case input
when DIRECTIONS[:left]
self.x -= 1
when DIRECTIONS[:up]
self.y -= 1
when DIRECTIONS[:right]
self.x += 1
when DIRECTIONS[:down]
self.y += 1
puts “Unknown direction”

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs