如何从Terminal.app运行一块ruby代码?

时间:2021-05-09 01:11:31

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

我特意使用OS X Terminal.app作为命令行的东西,但这个问题也可能适用于其他命令行工具。

Say I want to run this block of ruby code from the command line:

假设我想从命令行运行这个ruby代码块:

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.

现在,如果我复制/粘贴它只是分解并且不执行。

3 个解决方案

#1


1  

Please note that Terminal.app is not itself a Ruby interpreter. You'll want to fire up irb to get an interactive Ruby console:

请注意,Terminal.app本身不是Ruby解释器。你需要启动irb来获得交互式Ruby控制台:

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.

您可以使用其他技巧在特定脚本的上下文中运行irb。

#2


20  

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

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

#3


1  

Well first you need to run irb (or pass the code to the interpreter using ruby -e) as the terminal doesn't have any idea what that block of code is or how to interpret it.

首先,您需要运行irb(或使用ruby -e将代码传递给解释器),因为终端不知道该代码块是什么或如何解释它。

After that you should be able to run in by pasting it in as you say.

在那之后你应该能够像你说的那样粘贴它。

#1


1  

Please note that Terminal.app is not itself a Ruby interpreter. You'll want to fire up irb to get an interactive Ruby console:

请注意,Terminal.app本身不是Ruby解释器。你需要启动irb来获得交互式Ruby控制台:

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.

您可以使用其他技巧在特定脚本的上下文中运行irb。

#2


20  

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

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

#3


1  

Well first you need to run irb (or pass the code to the interpreter using ruby -e) as the terminal doesn't have any idea what that block of code is or how to interpret it.

首先,您需要运行irb(或使用ruby -e将代码传递给解释器),因为终端不知道该代码块是什么或如何解释它。

After that you should be able to run in by pasting it in as you say.

在那之后你应该能够像你说的那样粘贴它。