7stud -- wrote:
> 
> Look at this example:
> 
> def my_meth
>   prices = [2.5, 1.24, 6.80]
>   return prices
> end
> 
> def show(arr)
>   str = arr.join(", ")
>   puts str
> end
> 
> 
> user_prices = my_meth
> show(user_prices)
> 
> 

One other thing, a method call in your code is replaced by the return 
value of the method.  So the call to my_meth in the code above will get 
replaced by the return value of my_meth.  So when you execute your 
program, the line:

user_prices = my_meth

will become:

user_prices = [2.5, 1.24, 6.80]

If a method doesn't have a return statement, then the value of the last 
expression that was executed will be returned.  In the show() method, 
the last expression that's executed is the puts statement, and puts 
returns the value nil.  You can alter the code to see that:

return_val = show(user_prices)
puts return_val

--output:--
nil



However, since the original example just says:

show(user_prices)


and a method call is replaced by its return value, and because show() 
does not have a return statement and therefore the value of the last 
expression is returned, and the last expression that is executed is 
puts, the method call is replaced in the code with nil.  So the line:

show(user_prices)

becomes:

nil

That may look strange having nil sitting on a line by itself, but you 
can write a program like this:

puts "starting program"
10
nil
"hello"
puts "ending program"

--output:--
starting program
ending program

Values sitting on lines by themselves are simply discarded.  That 
program is equivalent to:

def meth1
  return 10
end

def meth2
  return nil
end

def meth3
  return 'hello'
end

puts "starting program"
meth1
meth2
meth3
puts "ending program"

If you call a method and don't store the return value in a variable, the 
return value is discarded.  However, instead of this:

def my_meth
  prices = [2.5, 1.24, 6.80]
  return prices
end

def show(arr)
  str = arr.join(", ")
  puts str
end


user_prices = my_meth  #<----*****this here
show(user_prices)

You could simply write:

show(my_meth)

The method call my_meth gets replaced in the code by its return value 
which is the array [2.5, 1.24, 6.80].  Therefore, the line:

show(my_meth)

becomes:

show([2.5, 1.24, 6.80])

However, its clearer if you use two statements:

user_prices = my_meth
show(user_prices)

...and clarity trumps brevity every time.








-- 
Posted via http://www.ruby-forum.com/.