什么时候在Ruby中使用Struct而不是Hash? [英] When to use Struct instead of Hash in Ruby?

查看:101
本文介绍了什么时候在Ruby中使用Struct而不是Hash?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有太多编程经验。但是,对我来说,Struct看起来有点类似于Hash。




  • Struct可以做什么?

  • 有什么结构可以做,哈希不能做什么?



在谷歌搜索后,结构的概念在C中很重要,但是我对C的了解不多。

解决方案

结构不同于以下方式使用hashmaps(除了代码的外观):


  • 一个结构具有一组固定的属性,而您将新的键添加到散列。

  • 调用结构实例中不存在的属性将导致NoMethodError,而从哈希中获取不存在的键的值将返回nil。

  • 即使结构具有相同的属性并且实例具有相同的值(即 Struct.new(:x).new(42)== Struct.new()),两个不同结构的实例永远不会相等。 :x).new(42)为false,而 Foo = Struct.new(:x); Foo.new(42)== Foo.new(42)为真)。

  • to_a 方法返回一个值的数组,而散列上的 to_a 则得到一个键值对的数组(其中pair表示二元数组 )

  • 如果 Foo = Struct.new(:x,:y,:z)您可以做 Foo.new(1,2,3)创建一个 Foo 的实例,而不必拼出属性名称。



  • $ b

    所以要回答这个问题:当你想用一组已知属性建模对象时,使用结构体。当你想要建模任意使用hashmaps时(例如,计算每个单词出现在字符串中的频率或将昵称映射到全名等等)肯定不是结构的工作,而建模一个名字,年龄和地址的人会是一个完美的适合 Person = Struct.new(名字,年龄,地址))。

    C结构与ruby结构几乎没有任何关系,所以不要让自己被这个混淆。


    I don't have much programming experience. But, to me, Struct seems somewhat similar to Hash.

    • What can Struct do well?
    • Is there anything Struct can do, that Hash cannot do?

    After googling, the concept of Struct is important in C, but I don't know much about C.

    解决方案

    Structs differ from using hashmaps in the following ways (in addition to how the code looks):

    • A struct has a fixed set of attributes, while you add new keys to a hash.
    • Calling an attribute that does not exist on an instance of a struct will cause a NoMethodError, while getting the value for a non-existing key from a hash will just return nil.
    • Two instances of different structs will never be equal even if the structs have the same attributes and the instances have the same values (i.e. Struct.new(:x).new(42) == Struct.new(:x).new(42) is false, whereas Foo = Struct.new(:x); Foo.new(42)==Foo.new(42) is true).
    • The to_a method for structs returns an array of values, while to_a on a hash gets you an array of key-value-pairs (where "pair" means "two-element array")
    • If Foo = Struct.new(:x, :y, :z) you can do Foo.new(1,2,3) to create an instance of Foo without having to spell out the attribute names.

    So to answer the question: When you want to model objects with a known set of attributes, use structs. When you want to model arbitrary use hashmaps (e.g. counting how often each word occurs in a string or mapping nicknames to full names etc. are definitely not jobs for a struct, while modeling a person with a name, an age and an address would be a perfect fit for Person = Struct.new(name, age, address)).

    As a sidenote: C structs have little to nothing to do with ruby structs, so don't let yourself get confused by that.

    这篇关于什么时候在Ruby中使用Struct而不是Hash?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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