如何非现有的哈希键返回空字符串?

时间:2013-06-28 08:13:12

标签: ruby ruby-on-rails-4 savon

这是确切的问题;

$ hash
=> {:createAuthenticationTokenRequest=>{:playerSessionID=>"111"}}

$ hash[:attributes!]
=> ""  (here is the crazy result)

$ hash.class
=> Hash

$ hash.keys
=> [:createAuthenticationTokenRequest]

这里发生了什么?对于不存在的哈希键,我不应该为nil?

详细问题:

我正在使用savon发送webservice请求并且始终“无法将Symbol转换为Integer”错误,使用pry调试错误显示该行正在执行为空字符串,它不应该执行。

attributes = hash[:attributes!] || {}

帮帮我吧!

提前谢谢,干杯!

更新: 回答如何创建哈希;

class Gyoku::Hash
  def self.iterate_with_xml(hash)
    xml = Builder::XmlMarkup.new
    attributes = hash[:attributes!] || {}

UPDATE2: 这是我发送的请求

request(
      createAuthenticationTokenRequest: {
        playerSessionID: "111"
      }
    )

正如我前面提到的,这是执行的savon gem代码。我试着把这个问题写成尽可能少的无聊,并且不知道为什么它会被投票:/

这是调试的源代码。

https://github.com/savonrb/gyoku/blob/master/lib/gyoku/hash.rb

2 个答案:

答案 0 :(得分:0)

我想我应该被投票......

请勿在代码中执行此操作,

def default_request_parameters
  @default_request_parameters || Hash.new('')
end

答案 1 :(得分:0)

  

您可以像这样创建一个哈希

     

方式1:

     

new_hash = Hash.new {| h,k | h [k] =“”}

     

new_hash [ 'unknown_key']

     

它返回

     

=> “”

     

new_hash.keys

     

=> [ 'unknown_key']

     

这会在散列中添加'unknown_key'键。

     

方式2:

     

hash2 = Hash.new(“”)

     

HASH2 [ 'unknown_key']

     

它返回

     

=> “”

     

但没有添加任何键。

     

hash2.keys

     

它返回

     

=> []