`
jsntghf
  • 浏览: 2482213 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

Struct和OpenStruct

阅读更多

Ruby的Struct用于快速将很多属性一起绑定到对象上。

 

#定义
class Man < Struct.new(:name, :age)

end

#使用
man = Man.new("allen", 24)
puts "#{man.name} is #{man.age} years old" # => allen is 24 years old

 

还有一种更强大的,OpenStruct可以动态的绑定属性。

 

require 'ostruct'

record = OpenStruct.new
record.name = "John Smith"
record.age = 70
record.pension = 300

puts record.name     # => "John Smith"
puts record.address  # => nil

#还可以支持用hash构建对象
 hash = { "country" => "Australia", :population => 20_000_000 }
 data = OpenStruct.new(hash)

 puts data   # => <OpenStruct country="Australia" population=20000000>

#动态添加一个block
data.hello = Proc.new {puts "hello"}
data.hello.call   # => "hello"
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics