1 Replies - 2044 Views - Last Post: 10 October 2012 - 10:16 AM Rate Topic: -----

#1 salmanmanekia  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 10-October 12

How to create an Array in a Hash

Posted 10 October 2012 - 09:57 AM

Hi,

I am new to Ruby and am working on Anagram. So in anagram for the input
below

# input: ['cars', 'four','scar', 'creams', 'scream', 'scream']

I want an output like this
# output: [ ["cars","scar"],
# ["four"],
# ["creams", "scream", "scream"] ]

But i am getting an output like
# output: [ ["cars","scar"],
# ["four"],
# ["creams", "scream"] ]

because of Hash property.

This is my code.
sorted_words = Hash.new(0)
words.each { |word| sorted_words[word]=word.downcase.chars.sort { |a, b|
a.casecmp(B)/> }.join
}
sorted_hash = {}
sorted_words.each_pair do |key, value|
  (sorted_hash[value] ||= []) << key
end

anagram_array = sorted_hash.values


Please advice me how to solve this. Thankyou for taking
you time out and helping with this amazing language

Is This A Good Question/Topic? 0
  • +

Replies To: How to create an Array in a Hash

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2117
  • View blog
  • Posts: 3,242
  • Joined: 21-June 11

Re: How to create an Array in a Hash

Posted 10 October 2012 - 10:16 AM

I'm not sure why you need the sorted_words hash (or why its default value is set to 0 - as far as I can see, you never use that default value). If you just store the words in sorted_hash directly, that should solve your problem and simplify your code.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1