The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Injecting a Hash Backwards and the Merge Block

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.
Injecting a Hash Backwards and the Merge Block Posted: Jan 25, 2006 11:17 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Red Handed.
Original Post: Injecting a Hash Backwards and the Merge Block
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

Here’s a fun snippet cooked up for the Camping 1.3 release due later today, laid out a bit nicer so you can play with it on your own.

Goal is: to parse a query string in as few bytes as possible. And to allow the Hash-like syntax from PHP and Rails.

 def qs_parse(qs)
   qs.split(/[&;]/n).
      inject({}) { |h,p| 
        k, v = p.split('=',2)
        h.merge(
          k.split(/[\]\[]+/).reverse.
            inject(v) { |x,i| {i=>x} }
        ){|_,o,n|o.merge(n)}
      }
 end

Believe me, there’s a real zen in the inner-inject/merge-block routine. Wield it like so:

 >> qs_parse("name=Philarp+Tremain&hair=sandy+blonde")
 => {"name"=>"Philarp+Tremain", "hair"=>"sandy+blonde"}
 >> qs_parse("post[id]=4&post[nick]=_why&post[message]=GROSS!&a=1")
 => {"a"=>"1", "post"=>{"message"=>"GROSS!", "nick"=>"_why", "id"=>"4"}}

Obviously, in the final version, stuff gets unescaped and all that. This exercise only focuses on parsing the structure. It would be nice for the merge-block to be tail recursive. It only goes one level presently.

Read: Injecting a Hash Backwards and the Merge Block

Topic: FastCGI, SCGI, and Apache: Background and Future at VMUNIX Blues Previous Topic   Next Topic Topic: Games of the week

Sponsored Links



Google
  Web Artima.com   

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