Search code examples
rubymethodsblock

Method taking an argument or a block


Is it possible to write a method that acts differently depending on the type of input? I'm trying to write one that acts like this

hello("derick")
#=> "hello derick!"

hello do
  "derick"
end
#=>"<hello>'derick'<hello/>"

Solution

  • Yes, it is possible in Ruby. Using block_given? you can check if a block is passed and execute the block else return any other result.

    def hello(s=nil)
      if block_given?
        "<hello>'#{yield}'</hello>"
      else
        "hello #{s}"
      end
    end
    
    puts hello("derick!")
    
    puts (hello do
      "derick"
    end)
    

    HTH