Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have multiple lines in the ruby interactive shell?

This might be a silly question. But, I am a newb... How can you have a multi-line code in the interactive ruby shell? It seems like you can only have one long line. Pressing enter runs the code. Is there anyway I can skip down to the next line without running the code? Again, sorry if this is a dumb question. Thanks.

like image 414
Zack Lipovetsky Avatar asked Aug 23 '14 18:08

Zack Lipovetsky


3 Answers

This is an example:

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 can tell us the result of the last expression it evaluated.

You can get more useful information from here(https://www.ruby-lang.org/en/documentation/quickstart/).

like image 155
pangpang Avatar answered Oct 13 '22 00:10

pangpang


One quick way to do this is to wrap the code in if true. Code will run when you close the if block.

if true
  User.where('foo > 1')
    .map { |u| u.username }
end
like image 31
colinta Avatar answered Oct 13 '22 00:10

colinta


If you are talking about entering a multi-line function, IRB won't register it until you enter the final end statement.

If you are talking about a lot of individual expressions such as

x = 1
y = 2
z = x + y

It's OK if IRB executes each as you enter it. The end result will be the same (for time-insensitive code of course). If you still want a sequence of expressions executed as fast as possible, you can simply define them inside of a function, and then run that function at the end.

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

f()
like image 23
14 revs, 12 users 16% Avatar answered Oct 13 '22 00:10

14 revs, 12 users 16%