Parens Down the Chute #
Robert Klemme used this inject
on the Ruby-Talk list today to emulate Hash#values
behavior:
>> h = {"a" => "111", "b" => "222"} => {"a" => "111", "b" => "222"} >> h.inject([]){ |a,(k,v)| a << k << v } => ["a", "111", "b", "222"]
Oh, man, using parens in block variable assignment is so classy. It’s one of those subtelties I constantly neglect. Perfect for Hash
iterators, since you usually get a tuple as a block argument.
>> h.each_with_index { |(k,v),i| ... } >> h.sort { |(ak,),(bk,)| ak <=> bk }
yerejm
>> h.sort { |(ak,),(bk,)| ak <=> bk }
I require a poignant explanation on that block variable assignment.
ak,
?why
Let me guess. Your real name is jeremy and you did an anagram on it.
Bheeshmar
yerejm, I believe the answer is given in the paragraph above the example:
So, (ak,) gets the key and value of the hash as a tuple and ignores the value.
why
Yes, it seems to me that you have only respellt Jeremy.
yerejm
Bheeshmar: Oh… you can ignore like that…
why: Is that… bad?
memmove
isn’t this more like the behavior of
or maybe like if we damn, I also neglect those parens too muchwhy
Naw, it’s cool. I’m just sayin, I have you figured out:
Asenchi
why: You are like a 10th degree blackbelt in Ruby. wow.
/me bows to your skillz.
why
hungry for a big burger
Destructuring assignment rules!
norseman
However, is there a way to do words like “jemery” or “jeemry” in one chained statement? Very neat entry, keep em coming. Also why doesn’t the plus character show up in preview/posts?
Comments are closed for this entry.