Sylar
Sylar

Reputation: 12082

Conditionals with multiple values in a key in a hash

cities = { 
 :birmingham => ['b31', 'b32', 'b33'],
 :walsall => ['ws1', 'ws2', 'ws3']
 }

I'm teaching myself Ruby and I came up with the above. I want to have an if statement:

if cities[:walsall] == 'ws1'
 puts "ws1 is a postcode of Walsall"
else
 puts "Your postcode was not found in the city you've typed"
end

Is there a way to get the above to true?

I cant find any documentation regarding the above hash.

Upvotes: 1

Views: 440

Answers (3)

Gagan Gami
Gagan Gami

Reputation: 10251

Try this:

 if cities.values[1].include?('ws1')
   puts "ws1 is a postcode of Walsall"
 else
   puts "Your postcode was not found in the city you've typed"
 end
#=> ws1 is a postcode of Walsall

Every Hash object has two methods: keys and values. The keys method returns an array of all the keys in the Hash. Similarly values returns an array of just the values.

For E.g

restaurant_menu = { "Ramen" => 3, "Dal Makhani" => 4, "Coffee" => 2 }
restaurant_menu.keys
=> ["Ramen", "Dal Makhani", "Coffee"]

Upvotes: 0

EdvardM
EdvardM

Reputation: 3072

Like BroiSatse indicated, Array has method include? which can be used to check for presence of an element. Actually all Enumerable types in Ruby have, so Hash and Set also support include?.

For the example you use, arrays are just fine. Note that if lists are large, then checking for presence of an element could become rather expensive. For such use cases, Set is much more suitable:

Set.new(['b31', 'b32', 'b33']).include?('b32') # true

Upvotes: 0

BroiSatse
BroiSatse

Reputation: 44685

Try:

if cities[:walsall].include? 'ws1'

Small advice: when you are looking for a suitable method, you can open up a console, get an object you expect should have the method you're looking for (In this case any array) and call:

`puts object.methods`     # In this case it would be [].methods

It will give you a whole list of methods available for given object. You can then get through them and check if any method name sounds good for what you need. You can then google it with ruby <object_class> <method name>. - This is the best way to learn new methods, and ruby offers seriously a lot of them.

Upvotes: 1

Related Questions