This post originated from an RSS feed registered with Ruby Buzz
by Red Handed.
Original Post: Hopscotching Arrays with Flip-Flops
Feed Title: RedHanded
Feed URL: http://redhanded.hobix.com/index.xml
Feed Description: sneaking Ruby through the system
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Red Handed
Latest Posts From RedHanded
Advertisement
Hehe. You’re going to love this! (Warning: some of you are going to hate this. ) Watch me skip every other element in an array with a flip-flop.
>> s = true
>> (1..10).reject { true if (s = !s) .. (s) }
=> [1, 3, 5, 7, 9]
Well, actually, that’s not so neat, since such a thing can simply be done with a single assignment in the block.
>> s = true
>> (1..10).reject { s = !s }
=> [1, 3, 5, 7, 9]
BUT! BUT ! Tell me, can you hop to every third element in an array using only booleans and assignment? My flip-flops can jump that much higher.
>> s = true
>> a = (1..10).reject { true if (s = !s) .. (s = !s) }
=> [1, 4, 7, 10]
Now, let’s see you beat this reassembling of our array into threes. My flip-flops bunch triplets together!
>> s = true
>> a = (1..10).inject([]) do |ary, v|
>> ary << [] unless (s = !s) .. (s = !s); ary.last << v; ary
>> end
=> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
Well, maybe this one you can beat with a modulo, but mine will be more detestable for sure.
Read: Hopscotching Arrays with Flip-Flops