每个3个值的数据集的Ruby解决方案

use*_*529 5 ruby arrays hash

所以我没有太多的Ruby知识,但需要处理一个简单的脚本.我会试着详细解释我的困境,但如果你还需要澄清,请告诉我.

我的脚本涉及每组3个数字.比方说,我们为每个人提供这三条信息:Age, Size, and Score.所以,我需要有一种方法来评估一个人是否存在某个年龄和大小.如果是这样,那么我想输出那个人的分数.

The only way I know of to keep track of this information is to create 3 separate arrays, each containing one piece of information. I can check if the age is included in one array, if so I can find its index (each value in each category will be unique -- so no "ages," "sizes," or "scores" will be repeated). I can then check if the value at the same index in the size array matches the specified size. If so, I can output the score found within the third array at the same index. I would prefer not to do it this way and, instead, to keep each person's age, size, and score together.

So, I've tried arrays within an array like this:

testarray = [
  [27, 8, 92],
  [52, 12, 84]
]
Run Code Online (Sandbox Code Playgroud)

The problem with this, however, is that I'm not sure how to access the values within those subarrays. So I know I could use something like testarray.include?(27) to check if 27 is present within the main array, but how would I check if 27 and 8 are the first two values within a subarray of testarray and, if so, then output the third value of the subarray, 92.

Then I tried an array of hashes, as below:

testarrayb = [
{ :age => 27, :size => 8, :score => 92 },
{ :age => 52, :size => 12, :score => 84 }
]
Run Code Online (Sandbox Code Playgroud)

I know I can use testarrayb[0][:score] to get 92 but how can I first check if the array contains a hash that has both the specified age and size and, if it does, output the score of that hash? Something similar to testarrayb[:age].include?(value) where the age of each hash is checked and then the size of the same hash is checked. If both match specified values, then the score of that hash is outputted.

如果有人能指出我正确的方向,我将非常感激.如果您推荐这种技术,请随意展示更高效和完全不同的技术.谢谢你的时间!

lwe*_*lwe 3

为什么不创建一个简单的类来表示您的数据,例如使用Struct. 然后提供一些类方法来处理过滤。

Entry = Struct.new(:age, :size, :score) do
  # Holds the data (example)
  def self.entries; @entries ||= [] end

  # Example filtering method
  def self.score_by_age_and_size(age, size)
    entry = entries.find { |e| e.age == age && e.size == size }
    entry.score if entry
  end
end

# Add some entries
Entry.entries << Entry.new(27, 8, 92)
Entry.entries << Entry.new(52, 13, 90)

# Get score
Entry.score_by_age_and_size(27, 8) # => 92
Entry.score_by_age_and_size(27, 34) # => nil
Run Code Online (Sandbox Code Playgroud)