I have a large amount of text pairs (no spaces inthe text) that I need to turn into a hash. Is there a shorcut that will allow me to create the hash without entering the quotes and arrows?
I have a large amount of text pairs (no spaces inthe text) that I need to turn into a hash. Is there a shorcut that will allow me to create the hash without entering the quotes and arrows?
Was this question a ringer or what? Seriously, I love how easy Ruby
makes some things. Come on Matz, fess up - this was a plant!
James Edward Gray II wrote:
···
On Dec 12, 2005, at 5:25 PM, Dan Diebolt wrote:
> I have a large amount of text pairs (no spaces inthe text) that I
> need to turn into a hash. Is there a shorcut that will allow me to
> create the hash without entering the quotes and arrows?
>
> %w(apple bananna orange grape)
> => ["apple", "bananna", "orange", "grape"]
>
> Hash["apple","bananna","orange","grape"]
> =>{"apple"=>"bananna", "orange"=>"grape"}
Thanks but what exactly is the asterisk doing (what's the receiver)?
That asterisk is Ruby "splat" or "explode" operator, in this context. The receiver is the Array, which is expanded back out into its individual elements (can only be used as the final parameter in a method call).
The * converts an array to a comma separated list (what David Black
dubbed the "unary unarray operator"). Therefore, it needs to be used in
a context where a comma separated list of the array's contents would
make syntactic sense. Also, for some reason (anyone know why?) it can't be
inserted anywhere other than at the end of an existing list, so that
e.g.
> ... in this context.=20
=20
Very clever. The hash's brackets disguise the context. I tried this con=
text but no joy:=20
=20
> *["apple", "bananna", "orange", "grape]