如何在ruby交互式shell中有多行?

时间:2014-08-23 18:10:46

标签: ruby-on-rails ruby interactive

这可能是一个愚蠢的问题。但是,我是一个新手...你怎么能在交互式ruby shell中有一个多行代码?看起来你只能有一条长线。按Enter键运行代码。无论如何我可以在不运行代码的情况下跳到下一行吗?再次,抱歉,如果这是一个愚蠢的问题。感谢。

3 个答案:

答案 0 :(得分:6)

这是一个例子:

2.1.2 :053 > a = 1
=> 1
2.1.2 :054 > b = 2
=> 2
2.1.2 :055 > a + b
 => 3
2.1.2 :056 > if a > b  #The code ‘if ..." starts the definition of the conditional statement. 
2.1.2 :057?>   puts "false"
2.1.2 :058?>   else
2.1.2 :059 >     puts "true"
2.1.2 :060?>   end     #The "end" tells Ruby we’re done the conditional statement.
"true"     # output
=> nil     # returned value

IRB可以告诉我们它评估的最后一个表达式的结果。

您可以从此处获取更多有用信息(https://www.ruby-lang.org/en/documentation/quickstart/)。

答案 1 :(得分:1)

如果您正在谈论输入多行功能,IRB不会注册,直到您输入最终的end声明。

如果你在谈论很多个人表达,比如

x = 1
y = 2
z = x + y

如果IRB在您输入时执行每项操作,那就没问题。最终结果将是相同的(当然,对时间不敏感的代码)。如果你仍然希望尽可能快地执行一系列表达式,你可以简单地在函数内部定义它们,然后在最后运行该函数。

def f()
    x = 1
    y = 2
    z = x + y
end

f()

答案 2 :(得分:0)

一种快速的方法是将代码包装在if true中。当您关闭if块时,代码将运行。

if true
  User.where('foo > 1')
    .map { |u| u.username }
end