Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm specifically using OS X Terminal.app for command line stuff, but this question may also apply to other command line tools.

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 that it just gets broken up and doesn't execute.

like image 239
Shpigford Avatar asked Jan 09 '12 21:01

Shpigford


2 Answers

ruby -e "Cats.each do |cat|
  cat.name = 'Mommy'

  cat.kittens each do |kitten|
    kitten.color = 'Brown'
  end
end"
like image 95
Jakub Hampl Avatar answered Sep 21 '22 16:09

Jakub Hampl


Please note that Terminal.app is not itself a Ruby interpreter. You'll want to fire up 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 you can use to run irb in the context of a particular script.

like image 43
Joseph Weissman Avatar answered Sep 21 '22 16:09

Joseph Weissman