SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Jan 2003
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Traversing a Data Structure in Ruby

    Data structures have always confused me. Either I get lost when I'm trying to access the nested elements or I just get frustrated take the easy way out to solve a problem.

    Let's say I have this hash of hashes:
    Code:
    config = {
           "somehost" => {
         	"user" => "bivouac",
         	"host" => "www.somehost.com",
         	"r_log" => "/home/bivouac/logs"
           },
           "another_host" => {
         	"user" => "someone_else",
         	"host" => "www.another_host.com",
         	"r_log" => "/var/tmp/logs"
           }
         }
    This is how I'm accessing the elements of the data structure via the command line:
    Code:
    machine = ARGV[0]
        user = config[machine]["user"]
        host = config[machine]["host"]
        r_log = config[machine]["r_log"]
        puts [user, host, r_log].join("\t")
    Seems too remedial. I already have the variable names (user, host, r_log) so it just seems overkill that I'm using them twice as var names and as hash keys. Anyway...

    This is the output:
    Code:
    $ ruby hash.rb somehost
      bivouac www.somehost.com		/home/bivouac/logs
    I was looking through the Ruby docs and the Pickaxe and I know that the 'hash' object has a 'each_key' method that you can use to access the keys of a hash, but what if those keys access another hash.

    Two questions really, what's a more elegant solution and anyone have a good tutorial on data structures could be in any language like PHP, Python or Perl. Just looking for better grounding when I run into these problems.

  2. #2
    SitePoint Evangelist
    Join Date
    Jun 2004
    Location
    California
    Posts
    440
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well you can check if a value is a hash by using the kind_of? and is_a? methods. The difference is that kind_of? returns true for children of the wanted class too. Example:

    Code:
    config.each do |key, value|
      if value.kind_of?(Hash) then
    	# is a hash
      end
    end
    Also, Hash#each allows you to use a key and value


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •