Hello,
I have this code and I am trying to pass the tests to look up the value of the hash to see if its there. How do I do it?
class FoodGroup
attr_reader :food
def initialize(food)
@food = food
end
food_groups = {
"grain" => ['Rice', 'Trigo', 'Avena', 'Barley', 'Flour'],
"vegetable" => ['Carrot', 'corn' 'Corn', 'Pumpkin', 'Papa'],
"fruit" => ['Apple', 'Mango', 'Strawberry', 'Peaches', 'Pineapple'],
"meat" => ['Res', 'Chicken', 'Salmon', 'Fish', 'Pig'],
"dairy" => ['Milk', 'Yogurt', 'Cheese', 'Cream']
}
def lookup()
p food
end
end
food_group = FoodGroup.new()
# Driver code
p food_group('Cream') == "dairy"
p food_group('Beef') == "meat"
p food_group('Pineapple') == "fruit"
p food_group('Cane') == "food not found”
Hashes are key-value data structures. So you need a key to fetch the value that you need. Then you need to look into that value for the keyword. There’s a method called “.include?” that you can use to check for a value in an array.
Here is an example:
$ irb
2.2.3 :001 > food_groups = {
2.2.3 :002 > "grain" => ['Rice', 'Trigo', 'Avena', 'Barley', 'Flour'],
2.2.3 :003 > "vegetable" => ['Carrot', 'corn' 'Corn', 'Pumpkin', 'Papa'],
2.2.3 :004 > "fruit" => ['Apple', 'Mango', 'Strawberry', 'Peaches', 'Pineapple'],
2.2.3 :005 > "meat" => ['Res', 'Chicken', 'Salmon', 'Fish', 'Pig'],
2.2.3 :006 > "dairy" => ['Milk', 'Yogurt', 'Cheese', 'Cream']
2.2.3 :007?> }
=> {"grain"=>["Rice", "Trigo", "Avena", "Barley", "Flour"], "vegetable"=>["Carrot", "cornCorn", "Pumpkin", "Papa"], "fruit"=>["Apple", "Mango", "Strawberry", "Peaches", "Pineapple"], "meat"=>["Res", "Chicken", "Salmon", "Fish", "Pig"], "dairy"=>["Milk", "Yogurt", "Cheese", "Cream”]}
2.2.3 :008 > food_groups["grain"].include? 'Rice'
=> true
2.2.3 :009 > food_groups["grain"].include? 'Spaghetti'
=> false
2.2.3 :010 >
Unsubscribe: <mailto:ruby-talk-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
Panagiotis (atmosx) Atmatzidis
email: atma@convalesco.org
URL: http://www.convalesco.org
GnuPG ID: 0x1A7BFEC5
gpg --keyserver pgp.mit.edu --recv-keys 1A7BFEC5
"Everyone thinks of changing the world, but no one thinks of changing himself.” - Leo Tolstoy
···
On 13 Aug 2016, at 02:04, Joseph Chambers <joseph@michael-chambers.com> wrote: