51224bdd17878b3b19e8987e9bb336a2

pls refer Following e.g

e.g

hsh = {"abba"=>"papa","ddd"=>{"gole"=>"cfr","say"=>"111"},"second"=>{"again"=>{"last"=>"kkkkk"} }}

o/p should be => 

["abba", "ddd.gole", "ddd.say", "second.again.last"]



#===============================================================================
following is my code which is half working.

def convert_deep_hash_into_string_of_keys(cast,str)
  str ||=[]
  a = ""
   cast.each do |k,v|
      if v.is_a?(Hash)
        a << k
        convert_deep_hash_into_string_of_keys(v,a)
      else
        a << k
      end
      str << ".#{a}"
      a = ""
    end
   str.each{|s| s.gsub!(/^\./,"")} 
   return  str.reverse
end
 
 hsh = {"abba"=>"papa","ddd"=>{"gole"=>"cfr","say"=>"111"},"second"=>{"again"=>{"last"=>"kkkkk"} }}

 convert_deep_hash_into_string_of_keys(hsh,[])

 o/p of above code => ["abba", "ddd.say.gole", "second.again.last"]

Refactorings

No refactoring yet !

E8f0d6e9bc8bca695b3c5bdf75cdcc03

Martin Plöger

July 27, 2009, July 27, 2009 12:59, permalink

No rating. Login to rate!

Hope this is right and reads (at least a bit ;-)) well...

Alternatively you could use Enumerable#map instead of Enumerable#collect (it is an alias but a little shorter => depends on your taste).
Also, I prefer checking for a method I'm calling instead of checking for the class (Duck Typing) => Better for testing/mocking etc. because you depend on a much smaller interface (just that method). Again, depends on your taste.

btw, why do you pass an Array as 2nd parameter? Do you need to concat the result to sth. else?

def convert x
  x.keys.collect do |k|
    [convert(x[k])].flatten.collect { |j| "#{k}#{".#{j}" if j}" }
  end.flatten if x.respond_to? :keys
end

#or this

def convert x
  x.keys.collect do |k|
    (res = convert x[k]) ? res.collect { |j| "#{k}.#{j}" } : "#[k}"
  end.flatten if x.respond_to? :keys
end
D41d8cd98f00b204e9800998ecf8427e

Desty Nova

August 6, 2009, August 06, 2009 21:48, permalink

1 rating. Login to rate!
h = {"abba"=>"papa","ddd"=>{"gole"=>"cfr","say"=>"111"},"second"=>{"again"=>{"last"=>"kkkkk"} }}

def convert(h)
  h.map{|k, v| v.is_a?(Hash) ? convert(v).map{|p| "#{k}.#{p}"} : k}.flatten
end

puts convert(h)

# =>
# second.again.last
# ddd.say
# ddd.gole
# abba
E8f0d6e9bc8bca695b3c5bdf75cdcc03

Martin Plöger

August 7, 2009, August 07, 2009 09:21, permalink

No rating. Login to rate!

@Desty Nova: Really nice, and great readability! Thumbs up!

Your refactoring





Format Copy from initial code

or Cancel