【问题标题】:Iterating over a hash with arrays as value以数组为值迭代哈希
【发布时间】:2019-06-03 03:19:00
【问题描述】:

我要求用户输入键 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 三次。

【问题讨论】:

  • 它是一个字符串,应该是哈希中的任何值
  • 我对学习编码和 ruby​​ 非常陌生——要学习的东西太多了,但我正在学习,我最终会到达那里。 :)

标签: ruby hash


【解决方案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

【讨论】:

  • 修正了错字。
  • 这将为mtahash 中的每个键运行一次。例如,current_line = 'n', current_station = '8th' => got it \n fish \n fish。这是预期的功能吗?
  • @Tom 它尽可能接近原始解决方案。
  • @mrzasa 只是好奇 fahz 会说他在寻找什么。没有什么反对你的答案。
  • 现在,是的,这是一次性运行@Tom
【解决方案2】:

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" 

【讨论】:

  • 这是可以理解的代码行,但仍然不起作用。无论输入是什么,输出总是fish 3次
  • @fahz 你说的是不可能的,请查看我的回答中的更新日志
  • 它在我的最后肯定不能工作..没有;除了鱼之外没有任何输出:(((((((
  • @fahz 因为你没有提供你的哈希值!例如n & 23rdn
  • 这是什么意思?哈希已在顶部定义..我也在尝试没有用户输入的代码我只是在硬编码它仍然无法正常工作 - 我做错了什么?
【解决方案3】:

我建议将 to_sym (String#to_sym) 的用户输入转换为 current_line,因为哈希键是符号。

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

最后通过键访问散列并检查数组是否包含(Array#includecurrent_station,因为散列的值是数组。

这只是一个 sn-p 的例子。

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


更好的是,反转输入序列,在用户进入线路后检查mtahash.has_key?,如果为真就去问站。

【讨论】:

    猜你喜欢
    • 2014-12-15
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 2011-02-28
    • 1970-01-01
    • 2013-04-30
    • 2019-04-06
    相关资源
    最近更新 更多