How can I run a ruby ​​code block from Terminal.app?

I use OS X Terminal.app for the command line, but this question can also apply to other command line tools.

Let's say I want to run this block of ruby ​​code from the command line:

Cats.each do |cat| cat.name = 'Mommy' cat.kittens each do |kitten| kitten.color = "Brown" end end 

Right now, if I copy / paste, it just breaks and fails.

+4
source share
3 answers

Note that Terminal.app itself is not a Ruby interpreter. You want to run irb to get an interactive Ruby console:

 user@host # irb irb(main):001:0> Cats.each do |cat| irb(main):002:1* cat.name = 'Mommy' irb(main):003:1> irb(main):004:1* cat.kittens each do |kitten| irb(main):005:2* kitten.color = "Brown" irb(main):006:2> end irb(main):007:1> end NameError: uninitialized constant Cats from (irb):1 from :0 

There are other tricks that you can use to run irb in the context of a particular script.

+1
source
 ruby -e "Cats.each do |cat| cat.name = 'Mommy' cat.kittens each do |kitten| kitten.color = 'Brown' end end" 
+20
source

Well, first you need to run irb (or pass the code to the interpreter using ruby -e ), because the terminal does not know what the code block is or how to interpret it.

After that, you can start by inserting it as you say.

+1
source

Source: https://habr.com/ru/post/1390125/


All Articles