How do I have my ruby script output what version of ruby is running it?
The RUBY_VERSION constant contains the version number of the ruby interpreter and RUBY_PATCHLEVEL contains the patchlevel, so this:
puts RUBY_VERSION
outputs e.g. 2.2.3, while this:
puts RUBY_PATCHLEVEL
outputs e.g. 173. Together it can be used like this:
ruby -e 'print "ruby #{ RUBY_VERSION }p#{ RUBY_PATCHLEVEL }"'
to output e.g. ruby 2.2.3p173
For reference, here's how variables and constants work, along with a list of Ruby's built-in variables and constants: Ruby Programming/Syntax/Variables and Constants and Pre-defined Variables.
You can get a list of all the global constants here, including RUBY_VERSION and friends, in the official Ruby language documentation.
For the bonus round, this will tell you some more useful info about your Ruby environment using RbConfig:
require 'rbconfig'
puts Config::CONFIG.sort_by{ |n,v| n.downcase }.map{ |n,v| "#{n} => '#{v}'" }
Related
I am trying to return the version of Ruby (such as 2.1.0) from a regular expression. Here's the string as it should be evaluated by a regular expression:
ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-darwin12.0]\n
How would I go about extracting 2.1.0 from this? It seems to me that the best way to do this would be to extract the numbers around two periods, but no spaces or characters around them. So basically, it would pull just 2.1.0 instead of anything else.
Any ideas?
How about:
str = "ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-darwin12.0]\n"
str[/[\d.]+/] # => "2.1.0"
[\d.]+ means "find a string of characters that are digits or '.'.
str[/[\d.]+/] will find the first such string that matches and return it. See String#[] for more information.
The question is, do all versions and Ruby interpreters return their version information consistently? If your code could end up running on something besides the stock Ruby you might have a problem if the -v output changes in a way that puts the version farther into the string and something else matches first.
TinMan, I think you need a more rigorous regex; e.g., "1..0"[/[\d.]+/] => "1..0", "2.0.0.1."[/[\d.]+/] => "2.0.0.1.", "2.0.0.0.1"[/[\d.]+/] => "2.0.0.0.1"
Ruby uses a similar style to Semantic Versioning, so the actual format of the string shouldn't vary, allowing a simple pattern. Where the version number occurs might not be defined though.
IF it went crazy, something like /[\d.]{3,5}/ should herd things back into some semblance of order, and normalize the returned value:
[
'foo 1.0 bar',
'foo 1.1.1 bar',
'foo 1.1.1.1 bar'
].map{ |s| s[/[\d.]{3,5}/] }
# => ["1.0", "1.1.1", "1.1.1"]
If you're trying to do this with running code, why not use the predefined constant RUBY_VERSION:
RUBY_VERSION # => "2.1.2"
Version numbers are notoriously difficult to grab, because there are so many different ways that people use to format them. Over the last several years we've seen some attempts to create some order and commonality.
Edit: I misread the question. I assumed the given string might be embedded in other text, but on re-reading I see that evidently is not the case. The regex given by #theTinMan is sufficient and preferred.tidE
This is one way:
str = "ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-darwin12.0]\n"
str[/[Rr]uby\s+(\d\.\d\.\d)/,1]
#=> "2.1.0"
This could instead be written:
str[/[Rr]uby\s+(\d(\.\d){2})/,1]
If matching "Ruby 2.1" or Ruby "2" were desired, one could use
str[/[Rr]uby\s+(\d(\.\d){,2})/,1] # match "2", "2.1" or "2.1.1"
or
str[/[Rr]uby\s+(\d(\.\d){1,2})/,1] # "2.1" or "2.1.1", but not "2"
Just Inspect RUBY_VERSION
Rather than parsing the output of whatever you're trying to parse, just inspect the RUBY_VERSION constant. On any recent Ruby, you should get output similar to the following in a REPL like irb or pry:
RUBY_VERSION
# => "2.1.0"
Or ask Ruby on the command line with:
$ ruby -e 'puts RUBY_VERSION'
2.1.0
Try this:
str = "ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-darwin12.0]\n"
pieces = str.split(" ", 3)
version, patch_num = pieces[1].split('p')
puts version
--output:--
2.1.0
I have a task of writing a simple Ruby script which would do the following.
Upon execution from the UNIX command line, it would present the user with a prompt at which he should be able to run certain commands, like "dir", "help" or "exit". Upon "exit" the user should return to the Unix shell.
I'm not asking for the solution; I would just like to know how this "shell" functionality can be implemented in Ruby. How do you present the user with a prompt and interpret commands.
I do not need a CLI script that takes arguments. I need something that creates a shell interface.
The type of program you require can easily be made with just a few simple constructs.
I know you're not asking for a solution, but I'll just give you a skeleton to start off and play around with:
#!/usr/bin/env ruby
def prnthelp
puts "Hello sir, what would you like to do?"
puts "1: dir"
puts "2: exit"
end
def loop
prnthelp
case gets.chomp.to_i
when 1 then puts "you chose dir!"
when 2 then puts "you chose exit!"
exit
end
loop
end
loop
Anyways, this is a simplistic example on how you could do it, but probably the book recommended in the comments is better. But this is just to get you off.
Some commands to get you started are:
somevar = gets
This gets user input. Maybe learn about some string methods to manipulate this input can do you some good. http://ruby-doc.org/core-2.0/String.html
chomp will chop off any whitespace, and to_i converts it to an integer.
Some commands to do Unix stuff:
system('ls -la') #=> outputs the output of that command
exit #=> exits the program
Anyways, if you want this kind of stuff, I think it's not a bad idea to look into http://www.codecademy.com/ basically they teach you Ruby by writing small scripts such as these. However, they maybe not be completely adapted to Unix commands, but user input and the likes are certainly handled.
Edit:
As pointed out do use this at the top of your script:
#!/usr/bin/env ruby
Edit:
Example of chomp vs. chop:
full_name = "My Name is Ravikanth\r\n"
full_name.chop! # => "My Name is Ravikanth"
Now if you run chop and there are no newline characters:
puts full_name #=> "My Name is Ravikanth"
full_name.chop! #=> "My Name is Ravikant"
versus:
puts full_name #=> "My Name is Ravikanth\r\n"
full_name.chomp! #=> "My Name is Ravikanth"
full_name.chomp! #=> "My Name is Ravikanth"
See: "Ruby Chop vs Chomp"
Here's a really basic loop:
#!/user/bin/ruby
#
while true do
print "$ "
$stdout.flush
inputs = gets.strip
puts "got your input: #{inputs}"
# Check for termination, like if they type in 'exit' or whatever...
# Run "system" on inputs like 'dir' or whatever...
end
As Stefan mentioned in a comment, this is a huge topic and there are scenarios that will make this complicated. This is, as I say, a very basic example.
Adding to the two other (valid) answers posted so far be wary of using #!/usr/bin/ruby, because ruby isn't always installed there. You can use this instead:
#!/usr/bin/env ruby
Or if you want warnings:
#!/usr/bin/env ruby -w
That way, your script will work irrespective of differences where ruby might be installed on your server and your laptop.
Edit: also, be sure to look into Thor and Rake.
http://whatisthor.com
http://rake.rubyforge.org
Use irb.
I was looking into an alternative to bash and was thinking along the same lines... but ended up choosing fish: http://fishshell.com/
Nonetheless, I was thinking of using irb and going along the lines of irbtools: https://github.com/janlelis/irbtools
Example:
> irb
Welcome to IRB. You are using ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-linux]. Have fun ;)
>> ls #=> ["bin", "share", "opt", "lib", "var", "etc", "src"]
>>
In any case, irb is the ruby shell.
Take a look at cliqr which comes with inbuilt support for build a custom shell https://github.com/anshulverma/cliqr/
If I run this in a 1.8.7 console:
$ irb-ruby-1.8.7-p330
1.8.7 :001 > "0a" =~ /\h\h/
=> nil
And if I run the same in a 1.9.2 console:
$ irb-ruby-1.9.2-p290
1.9.2p290 :001 > "0a" =~ /\h\h/
=> 0
:/
You're right that \h doesn't seem to be recognised by the standard Ruby 1.8.7 regexp library. This can be confirmed using Rubular. If you need 1.8 compatibility in your code without using any additional gems I think your only alternative is to use an equivalent character class [0-9a-fA-F].
I want to run a test file:
# xxx.rb
require 'test/unit'; class XTest < Test::Unit::TestCase; def test_xxx; end; end
Until ruby 1.9.2
ruby -Itest -e "require './xxx.rb'" - -v
did the job, with 1.9.3 I suddenly get:
/usr/local/rvm/rubies/ruby-1.9.3-rc1/lib/ruby/1.9.1/test/unit.rb:167:in
`block in non_options': file not found: - (ArgumentError)
(it tries to load the file '-' which does not exist)
Any ideas how to get the verbose mode back / to pass options to test::unit ?
Correct output would look like:
Loaded suite -e
Started
test_xxx(XTest): .
Try it with a double-dash:
ruby -Itest -e "require './xxx.rb'" -- -v
Or like this (no dashes, no require):
ruby -Itest xxx.rb -v
To explain, I think that in your example you are using a single dash which commonly means 'use stdin as a file'. You could do this, for example:
cat xxx.rb | ruby -Itest - -v
Double-dashes are used to stop argument parsing and hence pass the -v to test unit. As to why your example with a single dash worked up to 1.9.3... I'm guessing that prior to 1.9.3 ruby wasn't as strict when you specify stdin but don't have anything coming in on stdin (as you don't).
I'm working on implementing Project Euler solutions as semantic Ruby one-liners. It would be extremely useful if I could coerce Ruby to automatically puts the value of the last expression. Is there a way to do this? For example:
#!/usr/bin/env ruby -Ilib -rrubygems -reuler
1.upto(100).into {|n| (n.sum.squared - n.map(&:squared).sum)
I realize I can simply puts the line, but for other reasons (I plan to eval the file in tests, to compare against the expected output) I would like to avoid an explicit puts. Also, it allots me an extra four characters for the solution. :)
Is there anything I can do?
You might try running it under irb instead of directly under a Ruby interpreter.
It seems like the options -f --noprompt --noverbose might be suitable (.
#!/usr/bin/env irb -f --noprompt --noverbose -Ilib -rrubygems -reuler
'put your one-liner here'
The options have these meanings:
-f: do not use .irbrc (or IRBRC)
--noverbose: do not display the source lines
--noprompt: do not prefix the output (e.g. with =>)
result = calculate_result
puts result if File.exist?(__FILE__)
result of eval is last executed operation just like any other code block in ruby
is doing
puts eval(file_contents)
an option for you?
EDIT
you can make use of eval's second parameter which is variables binding
try the following:
do_not_puts = true
eval(file_contents, binding)
and in the file:
....
result = final_result
if defined?(do_not_puts)
result
else
puts(result)
end
Is it an option to change the way you run scripts?
script.rb:
$_= 1.upto(100).into {|n| (n.sum.squared - n.map(&:squared).sum)
invoke with
echo nil.txt | /usr/bin/env/ruby -Ilib -rrubygems -reuler -p script.rb, where nil.txt is a file with a single newline.