Hash and Struct in Ruby

Hash的用法

h = Hash.new
h[:low] = 32.0
h[:low]
# => 32.0
h.low
#NoMethodError: undefined method `low' for {:low=>32.0}:Hash

Struct的用法

Struct 特别适合用于存储具有类似Excel表格结构 的数据,如果不想为此创建一个类的话。

require 'date'
# temperature struct
Reading = Struct.new(:date, :low, :high)
# Reading is a class
readings << Reading.new(Date.parse("1990-02-01"), 23.0, 24.0)

readings[0].low  # =>23.0
readings[0][:low] # =>23.0

Struct还可以接收一个块,可以在里面定义实例方法和类方法。

Reading = Struct.new(:date, :low, :high) do
  # mean calculate mean temperature
  def mean
    (high + low) / 2.0
  end
end

Resources

思考来自Effective Ruby中,第10条:推荐使用Struct而非Hash存储结构化数据。