Solving easy problems with Ruby

I got this problem from here

Implement a group_by_owners function that:

  • Accepts a hash containing the file owner name for each file name.
  • Returns a hash containing an array of file names for each owner name, in any order.

For example, for hash {‘Input.txt’ => ‘Randy’, ‘Code.py’ => ‘Stan’, ‘Output.txt’ => ‘Randy’} the group_by_owners function should return {‘Randy’ => [‘Input.txt’, ‘Output.txt’], ‘Stan’ => [‘Code.py’]}.

module FileOwners

  def self.group_by_owners(files)
    new_hash = {}
    files.each do |key, value|
      new_hash[value] = [] unless new_hash.has_key?(value)
      new_hash[value] << file[key]
    end
    new_hash
  end
end

files = {
  'Input.txt' => 'Randy',
  'Code.py' => 'Stan',
  'Output.txt' => 'Randy'
}
puts FileOwners.group_by_owners(files)

There is another way that we can manipulate the hash:

module FileOwners

  def self.group_by_owners(files)
    new_hash = {}
    files.each do |file|
      new_hash[file[1]] = [] unless new_hash.has_key?(file[1])
      new_hash[file[1]] << file[0]
    end
    new_hash
  end
end

files = {
  'Input.txt' => 'Randy',
  'Code.py' => 'Stan',
  'Output.txt' => 'Randy'
}
puts FileOwners.group_by_owners(files)

When you can each on a Hash or Map in Ruby without asking for the key and value as arguments in the block, you can access it through an array of the key/value pair. That’s how hashes are built deeeeeeeeep inside, with buckets etc.

All in all the first way is more explicit.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s