哈希has_key?句法 [英] Hash has_key? syntax

查看:105
本文介绍了哈希has_key?句法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个哈希:

pre $ $ c $ a $ {key:value}
b = {key =>value}
c = {:key =>value}

以上结果:

  a.has_key?(key)#=> false 
b.has_key?(key)#=> true
c.has_key?(key)#=> false

我的问题是:


  • 为什么?这是什么情况?

  • 如何获得 a b c 使用相同的语法来返回 true
>

解决方案

有字符串和符号。一个字符串不是一个符号。



这些散列包含一个符号作为键:

  {key:value} 
{:key => value}

这个散列包含一个字符串作为键:

  {key=>value} 

这就是为什么你的测试表现得和他们一样。

Rails有一个Hash包装器,名为 HashWithIndifferentAccess 。如果您有其中之一,则可以通过字符串或符号访问值。但是对于普通哈希来说,这是有区别的。

  requireactive_support / core_ext

h = {key: value}。with_indifferent_access

h.has_key?(:key)#=> true
h.has_key?(key)#=>真


I have three Hashes:

a = {key:"value"}
b = {"key"=>"value"}
c = {:key=>"value"}

And these results:

a.has_key?("key") # => false
b.has_key?("key") # => true
c.has_key?("key") # => false

My questions are:

  • Why? What is this behavior?
  • How can I get a, b and c to return true using the same syntax for all of them?

解决方案

There are strings and there are symbols. A string is not a symbol.

These hashes contain a symbol as a key:

{key: "value"}
{:key => "value"}

This hash contains a string as a key:

{"key"=>"value"}

That's why your tests behave like they do.

Rails has a wrapper for Hash, called HashWithIndifferentAccess. If you have one of those, you can access values by either strings or symbols. But for regular hashes, there's distinction.

require "active_support/core_ext"

h = {key: "value"}.with_indifferent_access

h.has_key?(:key) # => true
h.has_key?("key") # => true

这篇关于哈希has_key?句法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆