iswg iswg - 4 months ago 8
Ruby Question

Ruby: return vs puts

I'm trying to wrap my head around the difference between return and puts.
Say I have the following 2 methods.

Method 1:

def method array
array.each do |n|
v = n * n
return n if v.even?
end
end

puts method [1, 2, 3, 4] #=> 2


Method 2:

def method array
array.each do |n|
v = n * n
puts n if v.even?
end
end

method [1, 2, 3, 4] #=> 2, 4


So my question is what makes the first method return the first item (2) that meets the condition as opposed to returning the second one (4)?

Answer

As per given your code snip your using return statement inside first method so that it will exit from loop when v.even? condition is true.

def method array
  array.each do |n|
    v = n * n
    return n if v.even?
  end
end

That's why it is returning only 2

In second method your loop will be check each element and will return all elements when v.even? condition is true.

If you still have any concern please let me know.

Comments