What's the difference between gets.chomp() vs. STDIN.gets.chomp()? - ruby

Are they the same, or are there subtle differences between the two commands?

gets will use Kernel#gets, which first tries to read the contents of files passed in through ARGV. If there are no files in ARGV, it will use standard input instead (at which point it's the same as STDIN.gets.
Note: As echristopherson pointed out, Kernel#gets will actually fall back to $stdin, not STDIN. However, unless you assign $stdin to a different input stream, it will be identical to STDIN by default.
http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-gets

gets.chomp() = read ARGV first
STDIN.gets.chomp() = read user's input

If your color.rb file is
first, second, third = ARGV
puts "Your first fav color is: #{first}"
puts "Your second fav color is: #{second}"
puts "Your third fav color is: #{third}"
puts "what is your least fav color?"
least_fav_color = gets.chomp
puts "ok, i get it, you don't like #{least_fav_color} ?"
and you run in the terminal
$ ruby color.rb blue yellow green
it will throw an error (no such file error)
now replace 'gets.chomp' by 'stdin.gets.chomp' on the line below
least_fav_color = $stdin.gets.chomp
and run in the terminal the following command
$ ruby color.rb blue yellow green
then your program runs!!
Basically once you've started calling ARGV from the get go (as ARGV is designed to) gets.chomp can't do its job properly anymore. Time to bring in the big artillery: $stdin.gets.chomp

because
if there is stuff in ARGV, the default gets method tries to treat the first one as a file and read
from that. To read from the user's input (i.e., stdin) in such a situation, you have to use
it STDIN.gets explicitly.

Related

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?
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.
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
#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

Usage of "ARGV.first"

I was trying the following code:
user = ARGV.first # supposed to ask for user name
puts "Hi, #{user}. How do you like this?"
It does not print as expected. It only prints:
Hi, . Do you like me?
Can someone give me a hint on this?
argv holds the command line arguments.
./your_script.rb USER_NAME
… it has nothing to do with reading data from a prompt.
It looks like you are reading this tutorial. You need to read past the first three lines of code.
The code to read from the prompt is on line 7.
likes = $stdin.gets.chomp
Quentin's given a good answer but he's referring to the "Do you like me?" prompt.
There's no prompt for user name in the Ruby code.
You enter your user name by passing it as an argument to your script.
So, if your script is called "ext14.rb" (as in the tutorial) you would do...
roby ext14.rb Azat
This will put "Azat" in the first element of ARGV (ARGV[0] or ARGV.first) so the user_name variable will contain the string "Azat"

How do I combine gets.chomp and ARGV in Ruby? [duplicate]

This question already has answers here:
Using gets() gives "No such file or directory" error when I pass arguments to my script
(3 answers)
Closed 6 years ago.
I'm new to learning ruby and currently stuck on having ARGV and gets.chomp in the same script.
I want the script to unpack 3 arguments first then I'll ask a question (gets.chomp) and then print string which includes one of the ARGV and gets.chomp variables. In the terminal I'm setting the ARGV as one two three (example: ruby file1.rb one two three). Example below of code:
first, second, third = ARGV
puts "Your first variable is: #{first}"
puts "Your second variable is: #{second}"
puts "Your third variable is: #{third}"
This works exactly how I would expect. In the terminal, it gives me one, two and three as variables in first, second and third.
I've added in a puts "What is your favourite colour" and this prints out as expected but when I set a gets.chomp for the input, I get an error.
first, second, third = ARGV
puts "Your first variable is: #{first}"
puts "Your second variable is: #{second}"
puts "Your third variable is: #{third}"
puts "What is your favourite colour? "
colour = gets.chomp #this is where the error occurs
puts "So your favourite number is #{first} and you like the colour #{colour}."
^The bottom line is what I want to print but I get an error at gets.chomp
This is what the terminal prints:
$ ruby ex13.rb one two three
Your first variable is: one
Your second variable is: two
Your third variable is: three
What is your favourite colour?
ex13.rb:8:in `gets': No such file or directory - one (Errno::ENOENT)
from ex13.rb:8:in `gets'
from ex13.rb:8:in `<main>'
I hoped I've explained the above well enough and let me know if any more information is needed.
Any help will be greatly appreciated!
Thanks,
I answered a question about this yesterday, which you can read here, but to address your situation specifically:
After first, second, third = ARGV, call ARGV.clear to empty it out.
Alternatively you could do first, second, third = 3.times.map { ARGV.shift }
The reason is that gets reads from ARGV if there's anything in it. You need to empty ARGV out before calling gets.

How to tell STDIN to stop reading?

So I am studying Build Awesome Command-Line Applications in Ruby. On page 81, we're supposed to use STDIN to enter more than one task into a project.
File.open(global_options[:filename], 'a+') do |todo_file|
if task_names.empty?
puts "Reading new tasks from stdin..."
task_names = STDIN.readlines.map {|a| a.chomp}
end
tasks = 0
task_names.each do |task|
todo_file.puts [task, Time.now].join(', ')
tasks+=1
end
if tasks == 0
raise "You must provide tasks on the command-line or standard input"
end
end
The usual way to enter tasks into a project it's like this $todo new "Rake leaves but with the code above we can to what's in the example below.
It does work. But how do I tell STDIN to stop listening? The example on how to use it is this...
$ todo new
Rake leaves
Take out trash
Clean garage
Put away dishes
^D
What does the ^D represent?
It’s an end-of-file character. You can type this literally on Unix systems with Ctrl+D or on Windows with Ctrl+Z. The traditional way of displaying the Ctrl modifier is with a ^ prefix, e.g., ^D.
Be aware that this closes standard input entirely. If you want to read more data after entering these lines, you’ll need to check the input itself for a different delimiter—for instance, an empty line.
You can close STDIN by pressing Ctrl-d on Unix-like systems or Ctrl-z on Windows.
What does the ^6 represent?
Are you sure it says ^6 and not ^d? If so, that's probably a typo.

One liner in Ruby for displaying a prompt, getting input, and assigning to a variable?

Often I find myself doing the following:
print "Input text: "
input = gets.strip
Is there a graceful way to do this in one line? Something like:
puts "Input text: #{input = gets.strip}"
The problem with this is that it waits for the input before displaying the prompt. Any ideas?
I think going with something like what Marc-Andre suggested is going to be the way to go, but why bring in a whole ton of code when you can just define a two line function at the top of whatever script you're going to use:
def prompt(*args)
print(*args)
gets
end
name = prompt "Input name: "
Check out highline:
require "highline/import"
input = ask "Input text: "
One liner hack sure. Graceful...well not exactly.
input = [(print 'Name: '), gets.rstrip][1]
I know this question is old, but I though I'd show what I use as my standard method for getting input.
require 'readline'
def input(prompt="", newline=false)
prompt += "\n" if newline
Readline.readline(prompt, true).squeeze(" ").strip
end
This is really nice because if the user adds weird spaces at the end or in the beginning, it'll remove those, and it keeps a history of what they entered in the past (Change the true to false to not have it do that.). And, if ARGV is not empty, then gets will try to read from a file in ARGV, instead of getting input. Plus, Readline is part of the Ruby standard library so you don't have to install any gems. Also, you can't move your cursor when using gets, but you can with Readline.
And, I know the method isn't one line, but it is when you call it
name = input "What is your name? "
Following #Bryn's lead:
def prompt(default, *args)
print(*args)
result = gets.strip
return result.empty? ? default : result
end
The problem with your proposed solution is that the string to be printed can't be built until the input is read, stripped, and assigned. You could separate each line with a semicolon:
$ ruby -e 'print "Input text: "; input=gets.strip; puts input'
Input text: foo
foo
I found the Inquirer gem by chance and I really like it, I find it way more neat and easy to use than Highline, though it lacks of input validation by its own.
Your example can be written like this
require 'inquirer'
inputs = Ask.input 'Input text'

Resources