开发者

ruby noob: are hashes speedy and optimal for storage or should I make a tuple?

开发者 https://www.devze.com 2023-01-15 22:05 出处:网络
This is a pretty simple problem im working on in Ruby, but im a total noob so I want to learn the most correct solution. I have a list of data with a name and a value.开发者_开发问答 I need to remembe

This is a pretty simple problem im working on in Ruby, but im a total noob so I want to learn the most correct solution. I have a list of data with a name and a value.开发者_开发问答 I need to remember all those (obvious answer: hash). But, i also need to remember the order of this data. SO it looks like:

x=1
y=2
z=3

I was thinking about making an array of 1 element hashes:

[0 => {'x' => 1},
 1 => {'y' => 2},
 2 => {'z' => 3}]

Are hashes the best choice in this situation? Is there some reason they would be slow, or not optimal?


Use Ruby 1.9. Hashes are ordered here.


You could try OrderedHash from ActiveSupport or Dictionary using Ruby Facets.


Performance permitting, an associate array would work. An associative array is an array of arrays, with each sub-array containing two elements:

a = [
  [:x, 1],
  [:y, 2],
  [:z, 3],
]

You can use assoc to find a sub-array by its first element:

p a.assoc(:x)         # [:x, 1]
p a.assoc(:x).last    # 1

Or rassoc to find a sub-array by its last element:

p a.rassoc(2)          # [:y, 2]
p a.rassoc(2).first    # :y

Whether or not this approach will work for you depend upon the size of the list and how often you have to search it. On my machine, finding the last element in a 1000 element list takes about 100 microseconds.


Another approach is to use a plain, unordered (in Ruby <= 1.8.7) hash:

h = {
  :x => 1,
  :y => 2,
  :z => 3,
}

And order it at the time you do an operation where order matters:

sorted_h = h.sort_by do |key, value|
  key.to_s
end.each do |key, value|
  p [key, value]
end
# [:x, 1]
# [:y, 2]
# [:z, 3]

This approach is good for alphabetical or numerical ordering (for example). It's not so good for order of insertion.

0

精彩评论

暂无评论...
验证码 换一张
取 消