Access environment variable in IRB but not when running file - ruby

require 'io/console'
def test
IO.console.winsize
end
puts "1: test: #{test()}"
puts "2: env: #{ENV['COLUMNS']}"
When I run this, this is what I see in my console:
1: test: [23, 80]
2: env:
In other words, I'm not able to print out ENV['COLUMNS'] when I run the program
However, typing ENV['COLUMNS'] within IRB gives me a string equal to the terminal width.
I am wondering why this is the case.

Only variables that are exported by your shell will be available in a Ruby script:
$ ruby -e "puts ENV['COLUMNS']"
$ export COLUMNS
$ ruby -e "puts ENV['COLUMNS']"
80
this answer here presents a possible workaround (follow the first link and check out the yaml branch on Github)
here is an answer that presents a way to get the terminal size without using shell variables

Related

Mix input/output with Ruby IO?

I am hoping to write a small method that can interact with a subprocess (bash in this case) and should be able to both write commands and have those commands print their outback back to my shell when running the Ruby file.
So far, I can do something similar with this code:
require 'io/console'
#shell = IO.popen('/bin/bash', 'w')
def run(command)
puts command
#shell.puts command
puts 'Done'
end
run 'var=3'
run 'echo $var'
run 'sleep 2'
run 'ls docs'
#shell.close
And then when I run this code all of the Ruby code is printed first, and only later does any of the shell code get printed:
var=3
Done
echo $var
Done
sleep 2
Done
ls docs
Done
3
<ls output>
I was trying to read some of the tests for io/console as I'm almost certain there exists a really straightforward way to interact with a subprocess like this and get the output inline with the commands being run:
https://github.com/ruby/io-console/blob/master/test/io/console/test_io_console.rb

How to use 'ruby -e' to execute multiline program?

I want to execute program by 'ruby -e' but it executes program if it's in single line but it's not executing if it's multiple line and throws the error. For an example,
>ruby -e "puts 'rajagopalan'"
=>rajagopalan
but
>ruby -e "a=[1,2,3,4,5]
a.each do |i|
puts i
end
"
it throws the error that "a.each do |i|
The syntax of the command is incorrect.
"
Can someone guide me how to execute the mulitiline via ruby -e
I have attached image here
you can try here document in your shell command:
ruby <<END
a=[1,2,3,4,5]
a.each do |i|
puts i
end
END
Hope this helps....
Try this:
>ruby -e "a=[1,2,3,4,5]; a.each do |i| puts i; end"
Basic idea, use a semi-colon wherever a new-line would be needed.
This has nothing to do with Ruby. You need to read the manual of your terminal emulator and your shell and figure out how to escape newlines.
As can be seen in the error you posted, you get a shell prompt after the first line, so the shell clearly seems to think the command is finished. Ergo, the shell tries to interpret the Ruby commands as shell commands, which leads to the error.

Why is the --simple-prompt command not working?

I'm just starting with Ruby, so please bear with me. The problem is that when I enter --simple-prompt into irb on OS 10.10.3 terminal, I don't get the simple prompt, I get an error message:
irb(main):001:0> --simple-prompt
NameError: undefined local variable or method `simple' for main:Object
from (irb):1
from /usr/local/bin/irb:11:in `<main>'
I'm assuming that the following problem is related to the above in that -v, -cw, etc. don't seem to work either. Thanks for any help!
You seem to be confused about passing flags to commands vs issuing statements in a REPL.
To start irb with the --simple-prompt option enabled, pass it in like so:
$ irb --simple-prompt
>>
Then you should be able to execute Ruby code.
>> puts "hello world!"
hello world!
=> nil
>>
The issue is that the --simple-prompt is a command line option to toggle the prompt.
You can see this by typing exit to get out of IRB and then typing
irb --help
Which gives you something like this:
Usage: irb.rb [options] [programfile] [arguments]
-f Suppress read of ~/.irbrc
-m Bc mode (load mathn, fraction or matrix are available)
-d Set $DEBUG to true (same as `ruby -d')
-r load-module Same as `ruby -r'
-I path Specify $LOAD_PATH directory
-U Same as `ruby -U`
-E enc Same as `ruby -E`
-w Same as `ruby -w`
-W[level=2] Same as `ruby -W`
--context-mode n Set n[0-3] to method to create Binding Object,
when new workspace was created
--echo Show result(default)
--noecho Don't show result
--inspect Use `inspect' for output (default except for bc mode)
--noinspect Don't use inspect for output
--readline Use Readline extension module
--noreadline Don't use Readline extension module
--prompt prompt-mode/--prompt-mode prompt-mode
Switch prompt mode. Pre-defined prompt modes are
`default', `simple', `xmp' and `inf-ruby'
--inf-ruby-mode Use prompt appropriate for inf-ruby-mode on emacs.
Suppresses --readline.
--sample-book-mode/--simple-prompt
Simple prompt mode
--noprompt No prompt mode
--single-irb Share self with sub-irb.
--tracer Display trace for each execution of commands.
--back-trace-limit n
Display backtrace top n and tail n. The default
value is 16.
--irb_debug n Set internal debug level to n (not for popular use)
--verbose Show details
--noverbose Don't show details
-v, --version Print the version of irb
-h, --help Print help
-- Separate options of irb from the list of command-line args
The --sample-book-mode or --simple-prompt is used in a command like this:
irb --simple-prompt
You can also do:
irb --prompt simple
But you can not do these things inside of IRB.
There is a way to change the prompt inside IRB, though, by changing the #prompt variable.

Running several 'exec' in a ruby loop

I'm scanning a folder for audio files and converting them to mp3.
Works great in RUBY.
However, once the first transcoding is done, it stops the whole loop
Here's a breakdown of my code process.
def scanFolder
# lots of code above to get folder list, check for incorrect files etc..
audioFileList.each {
|getFile|
exec_command = "ffmpeg #{getFile} #{newFileName}"
exec exec_command
}
end
What's happening is that it's transcoding the first file it finds, then it stops the whole function. Is there a way to force it to continue?
The ffmpeg does run and finish correctly at the moment, so it's not breaking anything
exec replaces the current process by running the given command. Example:
2.0.0-p598 :001 > exec 'echo "hello"'
hello
shivam#bluegene:$
You can see how exec replaces the irb with system echo which then exits automatically.
Therefore try using system instead. Here the same example using system:
2.0.0-p598 :003 > system 'echo "hello"'
hello
=> true
2.0.0-p598 :004 >
You can see I am still in irb and its not exited after executing the command.
This makes your code as follows:
def scanFolder
# lots of code above to get folder list, check for incorrect files etc..
audioFileList.each {
|getFile|
exec_command = "ffmpeg #{getFile} #{newFileName}"
system exec_command
}
end
Along with shivam's answer about using system, the spawn method may also be useful here:
http://ruby-doc.org//core-2.1.5/Process.html#method-c-spawn

ruby executing remote scripts in one line. (like installing rvm)

install rvm in one line example:
user$ bash < <(curl -s https://rvm.beginrescueend.com/install/rvm)
Now, say I have a ruby scripts like this at http://blah.com/helloworld.rb
puts "what's ur name?"
name = gets.chomp
puts "hello world from web, #{name}"
I would like to achieve this it in my shell without creating a temp file in one line or even better one command.
wget http://blah.com/helloworld.rb; ruby helloworld.rb; rm helloworld.rb
I have tried this, but user prompt will be ignored because of earlier pipe.
curl -s http://blah.com/helloworld.rb | ruby
What's the correct way to executing a remote ruby script? Thanks!
Like this:
ruby < <(curl -s http://blah.com/helloworld.rb)
Ruby evaluates ruby code similarly to how bash evaluates shell code
Another Ruby option based on Calibre install for shell scripts:
ruby -e "require 'open-uri'; system open('http:// or local file').read"
The same for Ruby scripts:
ruby -e "require 'open-uri'; eval open('http:// or local file').read"
Edited: Fixed missing quote and added Ruby script execution
From http://brew.sh/:
ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)"
In your Ruby code, you have to reopen stdin and tie it to the controlling terminal device /dev/tty!
rubyscript="$( cat <<-'EOF'
puts "what's ur name?"
name = gets.chomp
puts "hello world from web, #{name}"
EOF
)"
ruby <(echo '$stdin.reopen(File.open("/dev/tty", "r"))'; echo "$rubyscript")

Resources