为什么 ruby 在针对 select-one 调用 to_sym 时抛出错误?

Why does ruby throw error when calling to_sym against a select-one?

当我针对 "select-one" 类型的元素调用 to_sym 时,我 运行 遇到错误。

  begin
    ["//select", "//input"].each do |t|
      puts 'finding input for : ' + t
      elements = all(:xpath, t)
      elements.each do |e|
        puts "found element #{e[:id]} of type #{e[:type]}" if @debug
        puts "to symbol result: " + e[:id].to_sym  #This line explodes
        #...
  rescue
    puts "failed to enter fields on #{@name}"
    raise
  end

我收到错误 "Failed to enter fields on pageName"。当我在 select-one 类型的元素上调用 to_sym 时会发生此错误。如何查明此错误的原因并解决它?

更新

根据@axeltetzlaff,我安装了 Pry。我注意到 values[salutation] returns nil 我期望下面给出的值:

[1] pry(#<Step>)> values[e[:salutation]]
=> nil
[2] pry(#<Step>)> values
=> {:z=>"z",
 :a=>"a",
 :b=>"b",
 :c=>"c",
 :d=>"d",
 :e=>"e",
 :f=>"f",
 :g=>"",
 :h=>"",
 :salutation=>"Mr.",#See...I have a value

更新2

我取出了我用于调试的 puts,问题消失了:

puts "to symbol result: " + e[:id].to_sym #This line explodes

代码不再在下一行中断。通过简单的推论,问题是我不能连接字符串和符号。我猜某处有一些 ruby 规则说我不能这样做,但我没有。

to_sym 将字符串转换为符号。例如,"a".to_sym 变为 :a

确保您的 e[:id] returns 是您调用 to_sym 方法的字符串对象。尝试检查:

puts e[:id].inspect
puts e[:id].class

更新:

您不能在 Ruby 中连接字符串和符号。这将引发 no implicit conversion of Symbol into String (TypeError) 异常。

而不是做:

puts "to symbol result: " + e[:id].to_sym

您可以像这样使用字符串插值来做同样的事情:

puts "to symbol result: #{e[:id].to_sym}"