Search code examples
rubyvariable-assignmentproc

Understanding procs in ruby


I'm puzzled over the following code:

Proc.new do |a|
    a.something "test"

    puts a.something
    puts "hello"
end

It doesn't throw any errors when it runs. However nothing is printed for either puts statement. I'm curious about the a.something "assignment". Perhaps this is a method call w/ parens omitted. What is happening in the above code?


Solution

  • Proc.new ...             # create a new proc
    
    Proc.new{ |a| ... }      # a new proc that takes a single param and names it "a"
    
    Proc.new do |a| ... end  # same thing, different syntax
    
    Proc.new do |a|
      a.something "test"     # invoke "something" method on "a", passing a string
      puts a.something       # invoke the "something" method on "a" with no params
                             # and then output the result as a string (call to_s)
      puts "hello"           # output a string
    end
    

    Since the last expression in the proc is puts, which always returns nil, the return value of the proc if it is ever invoked will be nil.

    irb(main):001:0> do_it = Proc.new{ |a| a.say_hi; 42 }
    #=> #<Proc:0x2d756f0@(irb):1>
    
    irb(main):002:0> class Person
    irb(main):003:1>   def say_hi
    irb(main):004:2>     puts "hi!"
    irb(main):005:2>   end
    irb(main):006:1> end
    
    irb(main):007:0> bob = Person.new
    #=> #<Person:0x2c1c168>
    
    irb(main):008:0> do_it.call(bob)  # invoke the proc, passing in bob
    hi!
    #=> 42                            # return value of the proc is 42
    
    irb(main):009:0> do_it[bob]       # alternative syntax for invocation
    hi!
    #=> 42