Search code examples
rubyirb

How to write block in IRB?


For example, I want to implement this code in IRB, but it has single-line input so I can get how to write block there.

a = [3, 2, 1]
a[3] = a[2] - 1

a.each do |elt|
  print elt+1
end

Solution

  • (Oh you mean IRB)

    If you enter something that will be on multiple lines, ruby will wait until the final end is completed before running the code:

    irb(main):001:0> def dostuff
    irb(main):002:1>   puts "things"
    irb(main):003:1> end
    => :dostuff
    irb(main):004:0> dostuff
    things
    => nil
    irb(main):005:0> 
    

    As you can see the number at the prompt changes depending on how deep the block-level is.