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?”
STDOUT.flush
city = gets.chomp
puts "The city is " + city
end

When calling in a separate way (from inside the same file):

Laby::Engine.new(nil, nil).check_input

it works as needed.

When I tried to call the same from another place
[project_root/bin/play.rb]

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

Laby::Engine.new(nil, 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
the
above code ?
Any idea? Thank you.

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

Kernel#gets
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
arguments).

Abinoam Jr.

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

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.

Jesus.

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
inputs:

def query_next_direction
STDOUT.flush
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
else
puts “Unknown direction”
end
end

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