Accessing hash values sorted by their keys 
Author Message
 Accessing hash values sorted by their keys

Is an elegant way of doing this?

h.keys.sort.each { |key|
  puts h[key]

Quote:
}

works but seems unneccarily complicated.

Is there some analogy to the following fortran 90 s{*filter*}t?

DIMENSION a (30, 40), i (5)
PARAMETER (i = (/5, 10, 15, 20, 25 /) )

x1 = a(1, :)
x2 = a(10, 2:40:2)
x3 = a(1:10, 2:40:2)
x4 = f(2, i)

! x1 through x4 are arrays
! x1 is 1st row of a
! x2 is every 2nd element of the 10th row starting with 2nd element
! x3 is every 2nd element of rows 1 through 10 "    "    "     "
! x4 is elements 5, 10, 15, 20, 25 of 2nd row

'h.sort[*][1].each' would be great...

Josef 'Jupp' Schugt
--
jupp (AT) gmx (DOT) de                             :.          .....:
                                                   ::..........::::::
http://www.*-*-*.com/                                 ::::::::::::::::::
                                                   ''''''''''     dxm



Sat, 03 Sep 2005 07:49:45 GMT  
 Accessing hash values sorted by their keys

Quote:

> Is an elegant way of doing this?

> h.keys.sort.each { |key|
>   puts h[key]
> }

> works but seems unneccarily complicated.

I don't think that this looks complicated, but here is an alternative:

h.sort will return an array of arrays.  Like this:

Quote:
>> h = { "name" => "Daniel", "field" => "Math" }

=> {"name"=>"Daniel", "field"=>"Math"}
Quote:
>> h.sort

=> [["field", "Math"], ["name", "Daniel"]]

So Hash#sort will sort by the keys and return a 2-dimmensional array.
So your snipet could be written as:

h.sort.each { |item|
    puts item[0]

Quote:
}

I don't know if you think that's any simpler.

But if all you really want is to print the key values, just do:

puts h.keys.sort

But I suspect that this is not what you really want to do and your snipet
was just an example.

--
Daniel Carrera
Graduate Teaching Assistant.  Math Dept.
University of Maryland.  (301) 405-5137



Sat, 03 Sep 2005 07:59:34 GMT  
 Accessing hash values sorted by their keys

Quote:

> So Hash#sort will sort by the keys and return a 2-dimmensional array.
> So your snipet could be written as:
> h.sort.each { |item|
>     puts item[0]
> }

Or,

  h.sort.each do |key, value|
    puts key
  end

Gavin



Sat, 03 Sep 2005 08:39:12 GMT  
 Accessing hash values sorted by their keys
Hello Josef,


JJS> Is an elegant way of doing this?

JJS> h.keys.sort.each { |key|
JJS>   puts h[key]
JJS> }

puts h[h.keys.sort]

JJS> works but seems unneccarily complicated.

JJS> Is there some analogy to the following Fortran 90 s{*filter*}t?

JJS> DIMENSION a (30, 40), i (5)
JJS> PARAMETER (i = (/5, 10, 15, 20, 25 /) )

JJS> x1 = a(1, :)
JJS> x2 = a(10, 2:40:2)
JJS> x3 = a(1:10, 2:40:2)
JJS> x4 = f(2, i)

JJS> ! x1 through x4 are arrays
JJS> ! x1 is 1st row of a
JJS> ! x2 is every 2nd element of the 10th row starting with 2nd element
JJS> ! x3 is every 2nd element of rows 1 through 10 "    "    "     "
JJS> ! x4 is elements 5, 10, 15, 20, 25 of 2nd row

JJS> 'h.sort[*][1].each' would be great...

you also can use Range for subscripring array. For a real work
with multidimensional arrays it is better to use specific extension,
NumericalArray? (i don't remember)

--
Best regards,



Sat, 03 Sep 2005 13:18:20 GMT  
 Accessing hash values sorted by their keys
Hello Bulat,


BZ> Hello Josef,


JJS>> Is an elegant way of doing this?

JJS>> h.keys.sort.each { |key|
JJS>>   puts h[key]
JJS>> }

BZ> puts h[h.keys.sort]

oh, sorry! this not work because hash key can be an array and
matz don't implemented alternative method because he don't have
a vivid name for it. so

puts h.keys.sort.map { |i| h[i] }

:)

--
Best regards,



Sat, 03 Sep 2005 13:33:19 GMT  
 Accessing hash values sorted by their keys

Quote:

> Is an elegant way of doing this?

> h.keys.sort.each { |key|
>   puts h[key]
> }

    #!/usr/bin/env ruby

    require 'rbtree' # an RAA package

    h = RBTree.new

    h['answer'] = 42
    h['hero']   = 'ford'

    h.each do |k,v|
      puts "#{k} -> #{v}"
    end

answer -> 42
hero -> ford

just like a hash, but ordered.

Quote:
> Is there some analogy to the following Fortran 90 s{*filter*}t?

http://www.*-*-*.com/ ~masa/ruby/index-e.html

-a

--
  ====================================
  | Ara Howard
  | NOAA Forecast Systems Laboratory
  | Information and Technology Services
  | Data Systems Group
  | R/FST 325 Broadway
  | Boulder, CO 80305-3328

  | Phone:  303-497-7238
  | Fax:    303-497-7259
  ====================================



Sat, 03 Sep 2005 15:18:49 GMT  
 Accessing hash values sorted by their keys

Quote:
>> BZ> puts h[h.keys.sort]

>> oh, sorry! this not work because hash key can be an array and
>> matz don't implemented alternative method because he don't have
>> a vivid name for it. so

Actually he has, and he has three.

if h.respond_to? :select        # 1.7 or later
  puts(*h.select(*h.keys.sort))
else
  puts(*h.indices(*h.keys.sort)) or
  puts(*h.indexes(*h.keys.sort))
end

                                                FUKUMOTO Atsushi



Sat, 03 Sep 2005 21:00:08 GMT  
 Accessing hash values sorted by their keys

Quote:

>> if h.respond_to? :select       # 1.7 or later

oops, that must have been
  if Hash.instance_methods.include? "select"  # 1.7 or later

Quote:
>>   puts(*h.select(*h.keys.sort))
>> else
>>   puts(*h.indices(*h.keys.sort)) or
>>   puts(*h.indexes(*h.keys.sort))
>> end

                                                FUKUMOTO Atsushi



Sun, 04 Sep 2005 03:05:58 GMT  
 Accessing hash values sorted by their keys
Hi!

* On 2003-03-17 22:04

Quote:
> 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

Quote:
}

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



Sun, 04 Sep 2005 04:37:40 GMT  
 
 [ 9 post ] 

 Relevant Pages 

1. Sorting a Hash by value of integer stored in the Hash

2. Hash.new(Hash.new) doesn't use Hash.new as default value

3. sort the hash keys

4. Checking hash key's and values, with case insensitivity

5. sorting a list of key value pairs

6. hash as key in hash

7. (or (gethash key table) (setf (gethash key table) new-value))

8. Accessing dicts key-by-key

9. GOBO - Sorting Hash tables

10. Sorting a Hash

11. Array = Hash.sort ... but sometimes not

12. Sort by hash element

 

 
Powered by phpBB® Forum Software