1

Could someone explain this piece of code of using splat operator with method?

def initialize(talk)
  @title, @length = *title_and_length(talk)
end
def title_and_length(talk)
  title = talk[/.*(?=\s)/]
  str_length = talk.split
  if str_length.last.downcase == "talk"
   length = LIGHTNING_TALK_LENGTH
  elsif str_length.last == "minutes"
   length = str_length[-2..-1].join.gsub!("minutes", ' ').to_i
  else
   fail ArgumentError, "invalid talk length"
  end
  [title, length]
end
2
  • 4
    Hard to tell without knowing what #title_and_length does/returns, but assuming it returns an array with the title and length that splat operator would be redundant there Commented Jul 19, 2020 at 14:44
  • Here are two common uses of the splat operator: 1. def m(n,*pets); pets; end. The method might be called m(1,"dog","cat","gerbil") #=> ["dog", "cat", "gerbil"] or a = ["dog","cat","gerbil"]; m(1,*a) #=> ["dog", "cat", "gerbil"]. 2. a = [3,4]; b= [5,6]; [1,2,*a,*b,7,8] #=> [1, 2, 3, 4, 5, 6, 7, 8]. In #1, when passing individual objects the splat operator converts them to the array pets in the body of the method. When calling the method m(1,*a) and in #2, the splat operator converts an array to a sequence of its elements. Commented Jul 19, 2020 at 21:37

1 Answer 1

4

That splat operator is not 'doing' anything here as the returned element is an array. Using the splat operator on a method that does not return an array transforms an assigned variable into an array. Example:

def output(params)
  p params
end

Calling without splat operator:

output(1)
=> 1

Calling with splat operator:

*output(1)
[1]

We see if we return the value rather than print it, an error occurs:

def output(params)
  params
end

output(1)
=> 1
*output(1)
SyntaxError: (irb): syntax error, unexpected '\n', expecting :: or '[' or '.'

As the splat expects a variable to be assigned to

o = *output(1)
=> [1]

This is how the splat operator expects to be bound to a variable. It takes the 'remaining' elements of an array and attempts to assign them to a variable. So if you remove the splat from the initialize method, you will see the same results. The original author may have included the splat to emphasise the method should be assigned to variables, but that's a guess.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.