Huibin Zhang
Huibin Zhang

Reputation: 1110

Returning a value of ruby is strange

could anyone tell me the return value of this function give the parameter listed blew:

def sequence(*enumerables)
    enumerables.each do |enumerable|
        print "#{enumerable},"
    end
end

a,b,c = [1,2,3],4..6,'a'..'e'

value = sequence(a,b,c)
print value

why the value is evaluated to be:

[[1,2,3],4..6,"a".."e"]

Upvotes: 1

Views: 90

Answers (3)

tadman
tadman

Reputation: 211590

Remember that the last thing left on the stack is the return value of your method. This is always the case. If the return value is important, you must pay close attention to how you exit from your method.

The each method returns what it has been iterating over. Since the each is the last statement in your method, stack-wise, that value gets returned.

You can fix this by returning nothing:

def sequence(*enumerables)
  enumerables.each do |enumerable|
    print "#{enumerable},"
  end

  return
end

This approach is generally frowned on as the return method seems out of place. If the caller of this method is not expecting any particular return value, then it's not necessary.

The alternative is to return something useful:

def sequence(*enumerables)
  enumerables.join(",")
end

puts sequence(a,b,c)

It's often the case that methods which do not set an expectation for a particular return value may return an arbitrary one.

Upvotes: 3

user229044
user229044

Reputation: 239311

You're returning enumerables, which is an array containing all the arguments to the method.

What did you expect value to contain? You haven't made any explicit attempt to return anything, so whatever value the last statement in the method resolves to "falls off" the method to become its return value.

Upvotes: 2

Kyle
Kyle

Reputation: 22258

enumerables is an array. The splat (*) operator causes this.

The return value of sequence is the return value of enumerables.each which is enumerables

A simple example:

def foo(*args)
  args
end

foo(1,2,3,4) == [1,2,3,4] # true

Upvotes: 3

Related Questions