6

How can we return value from ruby script?

#!/usr/bin/env ruby

a = "test"
a

How can we access the value of 'a' in Ubuntu terminal or java or c?

3
  • 4
    Print it. Ruby vars are just that: Ruby vars. You can also exit with a value. Commented Jan 21, 2015 at 19:45
  • @DaveNewton is correct you can use STDOUT which print and puts both utilize as $stdout. This will output to the standard output stream. You could also right the results to a file and parse the file after the script completes. Here is a nice little post on the subject of IO in Ruby Commented Jan 21, 2015 at 20:03
  • Supposing you don't have access to the script. You want to run any arbitrary ruby script, and output what it evaluates to AS THOUGH calling p or pp on the final value, but without being able to edit the script itself. Commented May 24, 2021 at 8:16

2 Answers 2

12

print your variable within ruby/python script, it can then be read from a shell script by example :

#!/bin/bash
ruby_var=$(ruby myrubyscript.rb)
python_var=$(python mypythonscript.py)

echo "$ruby_var"
echo "$python_var"

take care your ruby/python script only print this variable ( there are more complicated ways with named pipes by example for more interaction ).

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for +1 but my answer is out of subject given it is ruby. anyway , print in ruby or in python is the very same way.
4

If the value is an integer between 0 and 255, you can use the exit status

$ ruby -e 'var=42; exit var'
$ val=$?
$ echo $val
42

5 Comments

Is it possible to return the filename? Is there any other way to access the filename ?
Note that an exit status of anything other than zero indicates an error.
@krunalshah, you want philippe lhardy's answer to return a string from the child process to the shell.
@Ajedi32, by convention yes. But since there are 256 possible exit status, it can convey more information than the binary "success|failure" status.
@glennjackman Well, it's a little more than just convention. There are many commonly used Unix commands and processes into which this convention is heavily ingrained. For example, try running set -e in your terminal, then try that example in your answer again. My point is, while you technically can use the exit status to return values from Unix commands, I wouldn't recommend using it in a real application for anything other than error codes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.