浏览 1826 次
锁定老帖子 主题:Struct和OpenStruct
该帖已经被评为隐藏帖
|
|
---|---|
作者 | 正文 |
发表时间: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" 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |