问题描述
Ruby Struct 允许使用一组访问器生成实例:
# 创建一个以常量命名的结构体Customer = Struct.new(:name, :address) #=>顾客Customer.new("Dave", "123 Main") #=>#<客户姓名=戴夫",地址=123 Main">
这看起来既方便又强大,但是,Hash 做的事情非常相似:
Customer = {:name =>"戴夫", :address =>123 主要"}
在哪些实际情况下我应该更喜欢 Struct(以及为什么),以及在选择一种结构时有哪些注意事项或陷阱?
就个人而言,当我想让一段数据表现得像一个数据集合而不是在 Hash.
例如,我制作了一个从 Youtube 下载视频的脚本,在那里我有一个结构来表示视频并测试所有数据是否到位:
A Ruby Struct allows an instance to be generated with a set of accessors:
# Create a structure named by its constant
Customer = Struct.new(:name, :address) #=> Customer
Customer.new("Dave", "123 Main") #=> #<Customer name="Dave", address="123 Main">
This looks convenient and powerful, however, a Hash does something pretty similar:
Customer = {:name => "Dave", :address => "123 Main"}
What are the real-world situations where I should prefer a Struct (and why), and what are the caveats or pitfalls in choosing one over the other?
Personally I use a struct in cases when I want to make a piece of data act like a collection of data instead of loosely coupled under a Hash
.
For instance I've made a script that downloads videos from Youtube and in there I've a struct to represent a Video and to test whether all data is in place:
Video = Struct.new(:title, :video_id, :id) do
def to_s
"http://youtube.com/get_video.php?t=#{id}&video_id=#{video_id}&fmt=18"
end
def empty?
@title.nil? and @video_id.nil? and @id.nil?
end
end
Later on in my code I've a loop that goes through all rows in the videos source HTML-page until empty?
doesn't return true.
Another example I've seen is James Edward Gray IIs configuration class which uses OpenStruct
to easily add configuration variables loaded from an external file:
#!/usr/bin/env ruby -wKU
require "ostruct"
module Config
module_function
def load_config_file(path)
eval <<-END_CONFIG
config = OpenStruct.new
#{File.read(path)}
config
END_CONFIG
end
end
# configuration_file.rb
config.db = File.join(ENV['HOME'], '.cool-program.db')
config.user = ENV['USER']
# Usage:
Config = Config.load_config('configuration_file.rb')
Config.db # => /home/ba/.cool-program.db
Config.user # => ba
Config.non_existant # => Nil
The difference between Struct
and OpenStruct
is that Struct
only responds to the attributes that you've set, OpenStruct
responds to any attribute set - but those with no value set will return Nil
这篇关于什么时候在 Ruby 中使用 Struct 而不是 Hash 更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!