Duong Bach
Duong Bach

Reputation: 155

Understanding `do` ... `end`

I executed the following:

def add(x, y)
  return x+y
end

result = add(4, 5) do
  puts "heeeeyyy"
end

result #=> 9

I also change return to puts, but it gives the same result. Please explain to me.

Upvotes: 0

Views: 55

Answers (1)

lei liu
lei liu

Reputation: 2775

A block need to be yield, or it will not be executed

def add(x, y)
   yield if block_given?
   return x+y;
end

If you want to print the result in your block, then:

   def add(x, y)
       yield x+y if block_given?
       return x+y;
    end

   result = add(4, 5) do |result|
     puts result
   end

Upvotes: 1

Related Questions