我正在尝试循环并匹配以下字符串:
@custom_channels = { cnn: 2, abc: 90 }
然后我希望能够检查/匹配每个并返回频道号码(例如90):
listen_for /channel to (#{@custom_channels.join('|')})/i do |name|
change_channel @custom_channels[name.downcase]
end
我一直收到以下错误:
scraper.rb:5:in `<main>': undefined method `join' for {:cnn=>2, :abc=>90}:Hash (NoMethodError)
答案 0 :(得分:1)
试试这个:
1.9.3p0 :007 > channels = {:cnn=>2, :abc=>90}
=> {:cnn=>2, :abc=>90}
1.9.3p0 :008 > channels.keys
=> [:cnn, :abc]
1.9.3p0 :009 > channels.keys.each do |name|
1.9.3p0 :010 > puts channels[name]
1.9.3p0 :011?> end
2
90
=> [:cnn, :abc]
答案 1 :(得分:1)
如果我理解你的要求:
@custom_channels = { cnn: 2, abc: 90 }
channel_names = @custom_channels.keys.map(&:to_s)
listen_for /channel to (#{Regexp.union(channel_names)})/i do |name|
change_channel @custom_channels[name.to_sym]
end