Ray Ban
Ray Ban

Reputation: 67

Start Command Prompt with Ruby doesn't work

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?

Upvotes: 1

Views: 1245

Answers (3)

Amulya Tanksale
Amulya Tanksale

Reputation: 130

@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

Upvotes: 1

Holger Just
Holger Just

Reputation: 55778

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.

Upvotes: 3

Laurie
Laurie

Reputation: 162

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 

Upvotes: 1

Related Questions