From: Josef 'Jupp' Schugt Date: 2003-03-19T05:37:40+09:00 Subject: Re: Accessing hash values sorted by their keys Hi! * On 2003-03-17 22:04 * Josef 'Jupp' Schugt wrote: > h.keys.sort.each { |key| > puts h[key] > } Thanks for the different alternatives for that. I think that h.sort.each { |key, value| puts value } is the best version but different people prefer different coding styles. Actually the method that did entrouble me was: def print_sorted(hash, keys, separator) i = 0 while i < keys.length x = hash[keys[i]] if x.nil? puts "-" else print separator unless i == 0 print x.empty? ? '-' : x.join(', ') end i += 1 end end It was used in a script that illustrates the use of Periodic.rb. the hash contains all language versions of an elements name where. The language versions in turn are arrays because in some languages there is more than only one name for certain elements. The proposed solution did help me condense the above code to: def print_sorted(hash, separator) print hash.sort.map { |key, value| (value.nil? or value.empty?) ? '-' : value.join(', ') }.join(separator) end To me that looks more readable than the original version. Josef 'Jupp' Schugt -- jupp (AT) gmx (DOT) de :. .....: ::..........:::::: http://jupp.tux.nu :::::::::::::::::: '''''''''' dxm