What does *:: (asterisk double colon) do in Ruby?
Asked Answered
V

1

14

I was poking through the Rails code today and stumbled upon this snippet:

new_date(*::Date._parse(string, false).values_at(:year, :mon, :mday))

What does the asterisk-double-colon (or splat-double-colon if you will) in *::Date do?

Presumably it has something to do with the scope of a particularly-namespaced Date class... but it's necessary enough for the author to include it rather than just use the standard Date class.

Voss answered 6/1, 2013 at 23:27 Comment(0)
V
15

I was reading the code wrong; it's not a "*::" operator at all.

Here's what's happening:

  • Find the Date class in the global scope (::Date)
  • call _parse() to get a hash of values
  • call values_at to turn the hash into an array
  • use the asterisk operator in its typical function of turning an array into multiple arguments for a method call
  • call new_date(), passing the array elements in for its year, mon, and mday arguments.

The lack of space between the * and :: operators made it confusing. :-\

Voss answered 6/1, 2013 at 23:37 Comment(2)
The first bullet point should say "in the global scope". The current scope would be without the ::.Urethra
And that's an excellent example why sometimes, using local variables is a good idea.Cinderella

© 2022 - 2024 — McMap. All rights reserved.