我已经看过Ruby文档中有关struct,map,array和hash;的所有内容;但无论出于什么原因,都没有掌握如何做到这一点。我有两个问题。
我看到了这样的响应,但是并没有太大帮助。48
Zed表示也要使用地图功能,但也没有用。使用Ruby,最有效的方法是检查哈希中的任何键是否与Array中的任何值匹配
锻炼说明可以在这里找到。Ruby The Hard Way EX.48说明
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")
$ 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
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
Oh god its not working
#<struct Lexicon::Pair token=nil, key=nil>
...
...
您在这里遇到了几个问题。最重要的是,您的哈希不起作用;散列建立在具有唯一键的键值对上,因此您的散列实际上与以下内容相同:
hash = { :direction => "west", :verb => "stop"}
您最好按如下所示在哈希中交换键值对:
hash = { "north" => :direction, "south" => :direction,
"east" => :direction, "west" => :direction, "go" => :verb,
"stop" => :verb }
@words.map do |word|
hash.keys.include?(word) ? Pair.new(hash[word], word) : Pair.new(:error, word)
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句