hoodwink.d enhanced
RSS
2.0
XHTML
1.0

RedHanded

Parens Down the Chute #

by why in bits

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 }
said on 25 Jan 2005 at 12:11

>> h.sort { |(ak,),(bk,)| ak <=> bk }

I require a poignant explanation on that block variable assignment. ak,?

said on 25 Jan 2005 at 12:50

Let me guess. Your real name is jeremy and you did an anagram on it.

said on 25 Jan 2005 at 13:02

yerejm, I believe the answer is given in the paragraph above the example:

Perfect for Hash iterators, since you usually get a tuple as a block argument.

So, (ak,) gets the key and value of the hash as a tuple and ignores the value.

said on 25 Jan 2005 at 13:02

Yes, it seems to me that you have only respellt Jeremy.

said on 25 Jan 2005 at 14:07

Bheeshmar: Oh… you can ignore like that…

why: Is that… bad?

said on 25 Jan 2005 at 14:10

isn’t this more like the behavior of

h.to_a.flatten
or maybe like
Hash#to_a
if we
h.inject([]){ |a,(k,v)| a << [ k, v ] }
damn, I also neglect those parens too much

said on 25 Jan 2005 at 14:21

Naw, it’s cool. I’m just sayin, I have you figured out:

 "jeremy".split(//).sort_by { rand }.join
said on 25 Jan 2005 at 15:42

why: You are like a 10th degree blackbelt in Ruby. wow.

/me bows to your skillz.

said on 25 Jan 2005 at 16:08
 "board".split( /#with_hand/x )
said on 26 Jan 2005 at 02:47

Destructuring assignment rules!

said on 27 Jan 2005 at 12:51

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.