Splat arguments - Help Please!


#1

I'm having trouble understanding splat arguments. I have no problem with the code in the course and understand how it works with a string.

However, trying to practice more, I wanted to implement the splat argument to the cubertino code so a user could put in multiple numbers and receive them all cubed.


#original code
def cubertino(n)
  n ** 3
end 

cupertino (8)

=> 512

#with splat method

def cube(*num)
  num.each{|x| x ** 3}
end

cube(10, 30 ,40)

=>
10
30
40

I'm not sure what I am doing wrong, but the input is not cubed in the method meant to take in multiple inputs from a user.

Any help would be appreciated!


#2

I figured out how to do this with two methods, but was wondering if it could be simplified to one. The way I did it is as follows...

def cube(num)
  return num ** 3
end

def cubeit(*y)
  y.each {|x| puts"#{cube(x)}"}
end
  
cubeit(10,30,40)

=>
1000
27000
64000

#3

In mathematic terms, this is a function. So it is fair to write is as one, and call it, as you have done.

What we need to examine is the return from cubeit() in your first example.

num.each{|x| x ** 3}

The return from that block isn't accumulated or tabulated. Hence the parent method has no return value.


#4

This seems to work:

def cube(*y)
  y.each do |x|
    puts x ** 3
  end
end

cube(10, 30, 40)

=>
1000
27000
64000

#5

The OP worked it out.


#6