So I don't have much Ruby
knowledge but need to work on a simple script. I'll try to explain my dilemma in detail, but let me know if you still need clarification.
My script involves sets of 3 numbers each. Let's say, for example, we have these three pieces of information for each person: Age, Size, and Score
. So, I need to have a way of assessing if a person exists with a certain Age and Size. If so, then I would like to output the score of that person.
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]
]
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 }
]
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.
I'd appreciate extremely appreciate it if someone can point me in the right direction. Feel free to demonstrate a more efficient and completely different technique if that's what you'd recommend. Thanks for your time!
Why not create a simple class to represent your data, e.g. using Struct
. Then provide some class methods to handle the filtering.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With