gpt4 book ai didi

ruby - 什么时候在 Ruby 中使用 Struct 而不是 Hash 更好?

转载 作者:数据小太阳 更新时间:2023-10-29 06:21:51 24 4
gpt4 key购买 nike

Ruby Struct 允许使用一组访问器生成实例:

# Create a structure named by its constant
Customer = Struct.new(:name, :address) #=> Customer
Customer.new("Dave", "123 Main") #=> #<Customer name="Dave", address="123 Main">

这看起来方便且功能强大,但是,哈希的作用非常相似:

Customer = {:name => "Dave", :address => "123 Main"}

在哪些现实情况下我应该更喜欢 Struct(以及为什么),选择其中一个有哪些注意事项或陷阱?

最佳答案

就我个人而言,当我想让一段数据像一组数据而不是在 Hash 下松散耦合时,我会使用结构体。 .

例如,我制作了一个从 Youtube 下载视频的脚本,其中我有一个结构来表示视频并测试是否所有数据都已到位:


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

稍后在我的代码中,我有一个循环遍历视频源 HTML 页面中的所有行,直到 empty?。不返回 true。

我见过的另一个例子是 James Edward Gray IIs configuration class使用OpenStruct轻松添加从外部文件加载的配置变量:

#!/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

<a href="http://www.ruby-doc.org/core-1.8.7/classes/Struct.html" rel="noreferrer noopener nofollow">Struct</a>之间的区别和 <a href="http://www.ruby-doc.org/stdlib/libdoc/ostruct/rdoc/index.html" rel="noreferrer noopener nofollow">OpenStruct</a>是那个Struct仅响应您设置的属性,OpenStruct响应任何属性集 - 但那些没有设置值的将返回 Nil

关于ruby - 什么时候在 Ruby 中使用 Struct 而不是 Hash 更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/810243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com