10

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.

Zack Lipovetsky
  • 103
  • 1
  • 4
  • you can run a .rb file like so, [Ruby on Rails: Running a .rb file from IRB](http://stackoverflow.com/questions/6149850/ruby-on-rails-running-a-rb-file-from-irb) – Mike Aug 23 '14 at 18:12

3 Answers3

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

pangpang
  • 8,581
  • 11
  • 60
  • 96
3

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
colinta
  • 3,536
  • 1
  • 28
  • 18
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()
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
  • 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: http://labs.codecademy.com/#:workspace – Zack Lipovetsky Aug 23 '14 at 18:23
  • 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. – Martin Konecny Aug 23 '14 at 18:29