I need to execute a few lines of Ruby code directly from the terminal, but I can’t find the right parameter for it.
Can you explain how to do this using the Ruby console or other methods?
I need to execute a few lines of Ruby code directly from the terminal, but I can’t find the right parameter for it.
Can you explain how to do this using the Ruby console or other methods?
To run Ruby code directly from the terminal, the simplest way is to use the ruby command followed by the -e flag, which allows you to execute a string of Ruby code. Here’s an example:
ruby -e "puts 'Hello, world!'"
This will execute the given Ruby code and print Hello, world! to the terminal. It’s great for testing small snippets of Ruby code quickly without needing a script file.
Using Ruby Interactive Shell : If you’re looking to interactively run Ruby code and experiment with it in real time, you can use the interactive Ruby shell (irb). To start irb, simply type:
irb
This opens up an interactive Ruby console where you can type Ruby code and see the results instantly. For example:
irb
>> puts 'Hello from IRB'
Hello from IRB
This method is perfect if you want to test code or explore Ruby features in an interactive environment.
Both methods are excellent! Another common way to run Ruby code is to place it in a file and execute it with the ruby command.
For instance, if you save your Ruby code in a file called hello.rb, you can run it like this:
ruby hello.rb
This is the most common way to execute a complete Ruby script or project, as it keeps your code organized.