1

I can't get this to work with the Start Command Prompt with Ruby on windows. I got this simple programm:

puts "Whats your name?"
name = gets
puts "Hello" + name + ". How are you?"

But if I call it with "ruby program.rb", instead for waiting for my input, it just prints out:

Whats your name?
Helloputs "Whats your name?"
. How are you?

It is like the "gets" command is not been recognized. Why does this happen?

Ray Ban
  • 67
  • 8
  • Possible duplicate of [One liner in Ruby for displaying a prompt, getting input, and assigning to a variable?](https://stackoverflow.com/questions/2889720/one-liner-in-ruby-for-displaying-a-prompt-getting-input-and-assigning-to-a-var) – Đào Minh Hạt Oct 23 '17 at 16:46
  • 2
    That is not my question. It is like the gets command does not work. – Ray Ban Oct 23 '17 at 16:57

3 Answers3

3

It looks like you are (somehow) passing the name of your programm two times on the command line. Your described behavior is reproducible when you are running

ruby program.rb program.rb

This works the way it does since gets does not read from STDIN in all cases. Instead, it prefers to read the files mentioned on the command line first. Only if there is no additional file on the command line, gets falls back to read from STDIN

The question on why you are passing the filename of your ruby program twi times is unfortunately less clear. If you are not calling it that way on your own, this might be caused by some strange environment options in your shell or due to your Ruby setup.

Holger Just
  • 52,918
  • 14
  • 115
  • 123
1

I was curious as well, and found this link How does gets and gets.chomp in ruby work? Apparently it created a new line therefore could not find the name.

This seemed to work, (following the instructions in the link)

puts "Whats your name?"
name = gets
puts "Hello " + name.chomp + ". How are you?"

Have fun.

Also if you start using rails, you can also test in your console Example

> def test1 
>     ...code .. 
> end  

> test1 
Laurie
  • 162
  • 1
  • 11
  • Still, the command prompt should wait for my input. I want to type my name in, but it does not wait and just prints out the text. I really don't get why. – Ray Ban Oct 23 '17 at 17:07
  • 1
    In your console (irb)... try doing this... def test puts "Whats your name?" name = gets puts "Hello " + name.chomp + ". How are you?" end Then run test. It works for me. – Laurie Oct 23 '17 at 19:01
  • I also make a test.rb with the code... puts "Whats your name?" name = gets puts "Hello " + name.chomp + ". How are you?" ... it worked > ruby test.rb – Laurie Oct 23 '17 at 19:06
1

@Ray Ban I have used your code

puts "Whats your name?"
name = gets
puts "Hello" + name + ". How are you?"

in gets.rb file and run it using $ ruby gets.rb and it worked as expected.

I am using ruby-2.3.0

Amulya Tanksale
  • 130
  • 1
  • 10