How can I have multiple lines in a ruby ​​interactive shell?

This might be a silly question. But, I'm a beginner ... How can you have multi-line code in an interactive ruby ​​shell? It seems like you can only have one long line. Pressing enter runs the code. Is there anyway I can go to the next line without running the code? Again, sorry if this is a stupid question. Thank.

+5


source to share


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 were done the conditional statement.
"true"     # output
=> nil     # returned value

      



IRB can tell us the result of the last expression it evaluates.

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

+5


source


If you are talking about entering a multi-line function, IRB will not register it until you enter the final statement end

.

If you are talking about a lot of individual expressions like

x = 1
y = 2
z = x + y

      



It's okay if IRB is executed by everyone when you type it. The end result will be the same (excluding time, of course). If you still want a sequence of expressions to execute as quickly as possible, you can simply define them inside a function and then run that function at the end.

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

f()

      

+1


source


One of the quickest ways to do this - to wrap code if true

. The code will run when the block is closed if

.

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

      

0


source







All Articles