11

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.

1

3 Answers 3

6

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/).

Sign up to request clarification or add additional context in comments.

Comments

5

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

2 Comments

Or wrap it in begin … end. It's a little less strange than if true.
👍 I like this more. In five years, when I have my muscle memory retrained, on that day I will send you a mental thanks 😆
2

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()

2 Comments

That makes sense. Thanks! I guess what I was wondering was if I could have a separate run command similar to how the codeacademy labs site has it set up: labs.codecademy.com/#:workspace
Seems like they have some custom layer overtop of the ruby interpreter to batch all your commands at once. I'm not aware of simulating this in any way other that grouping your expressions into a function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.