I've looked at everything from the Ruby docs on struct, map, array & hash; but for whatever reason haven't grasped HOW to do this. I have two questions.
- What's a good way to see if an array and a hash have a value in common?
- From a hash, how could I find a value and "automatically" take it's key (or viceversa) and include them in a new instance of something else (e.g. Pair.new)?
I saw this SO response, but it wasn't much help...Learn Ruby Hard Way ex. 48
Also looked at this too, but it didn't work & Zed says to use map func... Using Ruby, what is the most efficient way to check if any key in a hash matches any values within an Array
The exercise instructions can be found here. Ruby The Hard Way EX.48 Instructions
MY CODE (try#2080)
class Lexicon
Pair = Struct.new(:token, :key)
def scan(stuff)
@words = stuff.split(" ")
return analyze
end
def analyze
hash = { :direction => "north", :direction => "south",
:direction => "east", :direction => "west", :verb => "go",
:verb => "stop"}
@words.map do |word|
if word == hash[:direction]
#i need something here that says if word matches a value in hash...
#assign matching key/value to a new instance of Pair
Pair.new(word)
else
*#puts to see if anything is sticking*
puts "Oh god its not working #{word}"
puts Pair[]
puts hash[:direction]
end
end
end
end
a = Lexicon.new()
a.scan("north mama jeffrey homie")
TERMINAL
$ ruby lexicon.rb
Oh god its not working north
#<struct Lexicon::Pair token=nil, key=nil>
west
Oh god its not working mama
#<struct Lexicon::Pair token=nil, key=nil>
west
Oh god its not working Jeffrey
#<struct Lexicon::Pair token=nil, key=nil>
west
Oh god its not working homie
#<struct Lexicon::Pair token=nil, key=nil>
west
MY CODE #2081 Same as above but,
hash.each do |k, v|
if v == @words
#i need something here that says if word matches a value in hash...
#assign matching key/value to a new instance of Pair
Pair.new(k,v)
else
puts "Oh god its not working"
puts Pair[]
puts hash[:direction]
puts @words
end
end
TERMINAL
Oh god its not working
#<struct Lexicon::Pair token=nil, key=nil>
...
...
hash, irb will say:hash => {:direction=>"west", :verb=>"stop"}. Do you see why?