From: "S.D" Date: 2008-05-31T01:50:33+09:00 Subject: Re: PHP to Ruby (associative array to Hash) Jörg W Mittag wrote:
S.D wrote:
  
In the following PHP function, both 'types' and 'groups' are associative 
arrays. I'm trying to rewrite this function in Ruby, using Hashes and I 
haven't yet got it right. If someone with some insight into PHP and Ruby 
could give it a look and see where my current code might be incorrect, I 
'd appreciate any pointers that might correct the results. The PHP 
function is working; the Ruby version is not (yet) working. TIA for any 
tips, criticism and suggestions that you can submit.

-- Steve

The original PHP function:
    
[...]
  
public function getTypes($group_type=false) {
  if(!$group_type) {
    return $this->types;
  }
  else {
    if(array_key_exists($group_type,$this->groups)) {
      foreach($this->types as $key => $mt) {
        if(in_array($key,$this->groups[$group_type])) {
          $types[$key] = $mt;
        }
      }
      return $types;
    }
    else {
      return false;
    }
  }
}

    

Hi Steve!

This is my take. I shuffled things around a bit, e.g. using constants
instead of variables, but you'll figure it out ...

def types group = nil
  return TYPES unless group
  return nil unless GROUPS.include? group
  Hash[*TYPES.select {|suffix, mime_type| GROUPS[group].include? suffix}.flatten]
end

HTH, 
    jwm
  
Hi Joerg,

Great example! I don't quite understand the pointer(*) notation you are using in ruby. How would "Hash[*TYPES.select" differ from "Hash[TYPES.select"?
Is one a pointer to the Hash and the other the Hash itself? I thought Ruby did not have pointers. When I remove the '*', I get the following error in irb:

ArgumentError: odd number of arguments for Hash

Can you tell me what the '*' before the TYPES in your example changes the reference to TYPES?

Also, I understand that you've converted TYPES and GROUPS to global Hashes, but the same notation should work if these globals were embedded in a class.

Assuming class members @types is a hash of mime types => mime descriptions and @groups is a hash of group type names => [array of file extensions]

My final result, that appears to work as the PHP function did, is this:

def getTypes(group_type=nil)
  return @types unless group_type
  return nil unless @groups.include? group_type
  Hash[*@types.select {|suffix_name,mime_type| @groups[group_type].include? suffix}.flatten]
end

Thanks for your great help.

-- Steve

P.S. - Do you have any spare cycles to take on some Ruby consulting work?