The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Hopscotching Arrays with Flip-Flops

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Red Handed

Posts: 1158
Nickname: redhanded
Registered: Dec, 2004

Red Handed is a Ruby-focused group blog.
Hopscotching Arrays with Flip-Flops Posted: May 16, 2005 4:11 PM
Reply to this message Reply

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

Topic: The gun is good. Previous Topic   Next Topic Topic: Parsing a RSS Feed

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use