遍历以数组为值的哈希

时间:2019-01-08 12:18:13

标签: ruby hash

我要向用户输入键currentline和值currentstation,以便将其与哈希进行比较,并显示要走的行。

mtahash = {
  n: ["timesq", "34thn", "28thn", "23rdn", "Union_Square", "8th"],
  l: ["8th", "6th", "Union_Square", "3rd", "1st"],
  s: ["Grand Central", "33rds", "28th", "23rds", "Union Square", "Astor Place"]
}

puts "Please enter your current station"
current_station = gets.chomp
puts "Please enter your current line"
current_line = gets.chomp

mtahash.each do |key, value|
  if key == current_line && value == current_station
    puts "got it"
  else
    puts "fish"
  end
end

无论输入什么,我的代码都会输出fish三次。

3 个答案:

答案 0 :(得分:1)

此迭代中的value是一个数组。您应该检查它是否包含站名,而不是是否相等。还可以使用key.to_s将键转换为字符串(现在是符号):

 mtahash.each do |key, value|
   if key.to_s == current_line && value.include?(current_station)
     puts "got it"
   else
     puts "fish"
   end
 end

答案 1 :(得分:0)

each将为每个键值进行迭代(即使找到一个匹配项),但是detect将在找到匹配项后停止。

我认为哈希键是唯一的,因此detect比使用each更好

mtahash.detect { |k, v| k.to_s == current_line && v.include?(current_station) } ? 'got it' : 'fish'

减少迭代次数。

 > mtahash = {:n=>["timesq", "34thn", "28thn", "23rdn", "Union_Square", "8th"], :l=>["8th", "6th", "Union_Square", "3rd", "1st"], :s=>["Grand Central", "33rds", "28th", "23rds", "Union Square", "Astor Place"]} 
 >   current_line, current_station = 'l', '3rd'
 => ["l", "3rd"] 

 > mtahash.detect { |k, v| k.to_s == current_line && v.include?(current_station) } ? 'got it' : 'fish'
 => "got it" 

 > current_line, current_station = 'l', '43rd'
 => ["l", "43rd"] 

 > mtahash.detect { |k, v| k.to_s == current_line && v.include?(current_station) } ? 'got it' : 'fish'
 => "fish" 

答案 2 :(得分:0)

我建议将用户输入的CREATE DEFINER=`root`@`localhost` FUNCTION `REMOVE_DUPLICATE_CHAR_FROM_STRING`(myString VARCHAR(50)) RETURNS varchar(50) CHARSET utf8mb4 COLLATE utf8mb4_general_ci NO SQL BEGIN DECLARE tempString VARCHAR(50) DEFAULT ''; DECLARE sPreviousChar VARCHAR(1); DECLARE sCurrentChar VARCHAR(1); DECLARE inti INTEGER DEFAULT 1; set tempString = myString; IF LENGTH(tempString) > 0 THEN WHILE(inti <= LENGTH(tempString)) DO SET sCurrentChar = SUBSTRING(tempString, inti, 1); IF inti > 1 THEN SET sPreviousChar = SUBSTRING(tempString, inti - 1, 1); IF sCurrentChar = sPreviousChar THEN SET tempString = CONCAT(LEFT(tempString, inti - 1), SUBSTRING(tempString, inti, 1000)); END IF; END IF; SET inti = inti + 1; END WHILE; RETURN (tempString); ELSE RETURN 0; END IF; END String#to_sym)转换为current_line,因为哈希键是符号。

然后检查哈希是否具有该键(Hash#has_key)。

最后通过键访问哈希,并检查数组是否包含to_symArray#include),因为哈希值是数组。

这只是一个示例。

current_station


更好的是,反转输入顺序,在用户进入线路后检查current_station = "timesq" # gets.chomp current_line = "n".to_sym # gets.chomp.to_sym <--- note .to_sym if mtahash.has_key? current_line if mtahash[current_line].include? current_station then puts "got it" else puts "fish" end else puts "no line" end ,如果为true,则去询问电台。