Ruby - How to use -r switch with ruby command line tool - ruby

I was trying to figure out how to work the command line switch -r.
My understanding is that the code is typed out as follows:
ruby -r*nameOfRequired*
I am finding that this is not the case. When I type out the above and press enter, the terminal expects an "end of input syntax" and does not continue.
What am I missing? Does there need to be a space in between the switch and the name of the required file?
Please and thank you!
EDIT:
I am currently reading "The Well Grounded Rubyist" by David A. Black, and I came up with this question while reading the section on command line switches.
Having said that, I created a "test.rb" file, containing:
puts Date.today
Then, in the terminal, I typed out:
ruby -r date
I thought this would 'require' the date module, and then enable me to run the "test.rb" file, using ruby test.rb (given that I am in the correct directory).
Instead, the terminal cursor moves to a newline, expecting more input. Let me know if I need to clarify anything else. Thanks!

If you just type ruby -rmodule, then Ruby will load the module and wait for you to type the main program that requires that module.
If you just want to run the module and do nothing else, you can do do rubyfull-path-to-module without the -r, or ruby -rmodule -e exit, or ruby -rmodule </dev/null, or similar.

In general, the ruby command does not record any state from one run to the next, so you need to tell it every thing that it needs to know whenever you run it.
Whenever you run it, you need to tell it the main program to run or else it will expect you to type that program on the standard input. The -r does not specify the main program.
Try this:
ruby -rdate test.rb

According to ruby -h:
-rlibrary require the library, before executing your script
Without giving your script file path, it read the script from stdin.
Try following (You can omit script file path when you give -e command):
ruby -r**nameOfRequired** -e ""

Related

How does this Ruby command line work? Seemingly running a CMD script with Ruby

I'm examining how ridk enable works in order to figure out how to hook it into Travis CI build logic. (The Ruby installation I'm studying is a RubyInstaller+Devkit installed locally; the commands are run from the "Start Command Prompt with Ruby" prompt.)
I've got stuck at a Ruby command line executed under the hood whose working is a mystery to me:
"C:\Ruby24-x64\bin\ruby" --disable-gems -x 'C:\Ruby24-x64\bin\ridk.cmd' enable
It seems to run a CMD script (?!) with Ruby -- which isn't supposed to be possible. Running it with -rtracer in place of --disable-gems shows that the execution somehow ends up jumping into C:/Ruby24-x64/lib/ruby/site_ruby/2.4.0/ruby_installer/runtime/ridk.rb.
Could someone explain to me how this command line works?
From man ruby:
-x[directory]
Tells Ruby that the script is embedded in a message. Leading garbage will be discarded until the first line that starts with #!
and contains the string, ruby
Any meaningful switches on that line
will be applied. The end of the script must be specified with either
EOF ^D ( control-D ^Z ( control-Z or the reserved word __END__ If the
directory name is specified, Ruby will switch to that directory before
executing script.
Which means the ridk.cmd has embedded ruby code.
The directory is optional, as indicated by both the square brackets around the name and the description. If provided, it should be directly after -x without any space, which effectively allows it to be an optional argument.

how to build wrapper script

Sort of an odd question, but: how would one go about creating a wrapper shell script that can be used in the #! line in other scripts.
wrap.sh
#!/bin/bash
set -e
echo "wrapper!"
exec ruby "$#"
test.rb
#!/usr/bin/env wrap.sh
puts RUBY_VERSION
puts "the ducks come from the trucks"
wrap.sh is in the path, and test.rb is marked as executable.
Now I do:
./test.rb
wrapper!
ruby: no Ruby script found in input (LoadError)
The goal is to execute the ruby script via the wrapper (The ruby version can be either local or comes from a traveling ruby install that is shipped along with the app).
As far as I can tell ruby is invoked, it's just unhappy with the #! in the test.rb and refuses to run the script. I cannot remove the #! because that's how the script is executed in the first place.
Any workarounds for this?
So, I cannot use rbenv/rvm/etc. There is more logic in the wrapper than this, but this is the gist of it.
Looks to me like the arguments are not being passed to Ruby in "$#". I don't think the bang-hash line is the problem.
I don't see anything in your script which actually passes the contents of test.rb to wrapper.sh, which is the bigger issue.
Perhaps the real problem can be solved by some other means? For example, is the problem you're trying to solve to run arbitrary commands prior to the invocation of any Ruby script from the command line? Perhaps it can be approached that way...
It looks like Ruby just checks that the hash-bang line contains "ruby": https://github.com/ruby/ruby/blob/v2_2_2/ruby.c#L1580 So basically having ruby somewhere in the #! line is all it takes.

Ruby: Keep console open after script execution

I wrote a Ruby script like the following example. The basic functionality is the same:
# get input from the user
input = gets.chomp
# do awesome stuf with this input and print the response
puts do_awesome_stuff(input)
The problem is when I run the script it prints the solution I want, but the console window closes right after. I want the console to keep open.
I'm currently on windows, but the solution should be working on every system.
One way is to run the ruby script with a .bat file and pause it, like so:
ruby script.rb
PAUSE
I hope there is a way without the additional .bat file. Does Ruby has a function like PASUE integrated?
It seems like you double click the ruby script file.
Instead issue the following command in cmd shell.
ruby filename.rb
If you don't want that, you can add gets to the end of the script.
# get input from the user
input = gets.chomp
# do awesome stuf with this input and print the response
puts do_awesome_stuff(input)
gets # <----
But this is not recommended because .. if you run the command in cmd shell or terminal you should type extra Enter to return to the shell.
Use the -r options of irb.
irb -r ./filename.rb

Ruby .gets doesn't work

I'm trying to get simple user input in Ruby, but I can't get it working. I'm using the gets method, but the program never stops to ask me for input. I'm using Sublime Text 2 as my text editor, and I run the program in it, too (if this makes a difference).
Here's my code:
puts "What is your name?"
name = gets
puts "Hello " + name + ". How are you?"
And here's the error (and output) given to me:
C:/Users/Sten Sootla/Desktop/Ruby workspace/exercise.rb:3:in `+': can't convert nil into String (TypeError)
from C:/Users/Sten Sootla/Desktop/Ruby workspace/exercise.rb:3:in `'
What is your name?
[Finished in 0.1s with exit code 1]
Why doesn't the program stop to ask me for input?
Try using $stdin.gets instead of just a plain gets, this will force the input to come from stdin
Here's how I understand it. gets and puts are instance methods of IO, and the default IOs are $stdout and $stdin.
Calls to gets/puts will only be effective if the translator is capable of handling stdout/in e.g. IRB
If you run a ruby file from bash it works too.
io_test.rb
puts gets
in bash
ruby io_test.rb
Then it will "put" into stdout whatever it "gets" from stdin.
If you want to run code within ST2, check out the SublimeREPL plugin, available through Package Control. While you can use IRB, its main Ruby interface is through pry, which is a lot more powerful. You can use it as a classic REPL (think Clojure or LISP), and you can also transfer your code from one tab into the running REPL in another tab by selection, line range, or block.
Interestingly, your code above works in IRB for me, but not pry for some reason - it's reading my $EDITOR environment variable, which is set to subl -w but failing with Errno::ENOENT: No such file or directory - subl -w. Strange...
At any rate, I highly highly recommend SublimeREPL, as it's a really powerful tool, and is self-contained within ST2, so you don't have to keep flipping back and forth to your terminal, saving and reloading your programs.

How do I read a file in Ruby using a specific script?

I am doing a series of tutorials on how to code in Ruby. I want to read a .txt file using this formula:
filename = ARGV.first
prompt = "> "
txt = File.open(filename)
puts "Here's your file: #{filename}"
puts txt.read()
puts "I'll also ask you to type it again:"
print prompt
file_again = STDIN.gets.chomp()
txt_again = File.open(file_again)
puts txt_again.read()
The text file reads:
This is stuff I typed into a file. It is really cool stuff.
Lots and lots of fun to have in here.
The name for the text file is ex15_sample.txt. I tried with the above formula, and nothing seems to work. I have a hard understanding how to use both ARGV and STDIN.gets.chomp.
What should I do? I ask that you use the formula above; this stuff is a little confusing, so for now, just use the formula above.
The script works. You're not explaining how you're trying to run the script or what errors you're seeing, so it's a bit hard to help you.
If you have a text file named ex15_sample.txt in the same directory as your script (let's call it script.rb), and if you have Ruby set up properly, then if you run it with
$ ruby script.rb ex15_sample.txt
everything should work fine.
If you're trying to change the first line to always use ex15_sample.txt, be sure to put it in quotes:
filename = "ex15_sample.txt" # Without the quotes, you'll get an error.
Again, it's hard to help you without knowing exactly how you're running the script or what errors you're getting.
Update: I seems your issue is that you aren't clear on how to run a Ruby script. The simplest way is to, at your system's command prompt, type ruby then a space, then the name of the file with a Ruby script in it. If your script is in a file named script.rb, you would type ruby script.rb. That won't work if your script is in a file with a different name. If the script is in a file named read-a-file.rb, then you need to type ruby read-a-file.rb.
This particular script wants a command line argument after the file name. If the text file you want to read is in a file named ex15_sample.txt, then you need to type that after the script name. In the previous example, the command would become ruby read-a-file.rb ex15_sample.txt. That will only work if the files are in the same directory (a.k.a. folder).

Resources