论坛首页 编程语言技术论坛

Struct和OpenStruct

浏览 1799 次
该帖已经被评为隐藏帖
作者 正文
   发表时间:2009-12-11  

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