替代类使用,节省代码,清晰简洁
使用Struct
SelectOption = Struct.new(:display, :value) do
def to_ary
[display, value]
end
end
option_struct = SelectOption.new("Canada (CAD)", :cad)
puts option_struct.display
# Canada (CAD)
puts option_struct.to_ary.inspect
# ["Canada (CAD)", :cad]
使用类
class SelectOption
attr_accessor :display, :value
def initialize(display, value)
@display = display
@value = value
end
def to_ary
[display, value]
end
end
option_struct = SelectOption.new("USA (USD)", :usd)
puts option_struct.display
# USA (USD)
puts option_struct.to_ary.inspect
# ["USA (USD)", :usd]
临时的数据结构
例如一个使用两个日期来过滤表单数据的例子,你可以在过滤的地方使用两个值,也可以创建一个FilterRange Struct结构, 这个结构有一个from_date和to_date属性, 你或许需要一个方法来统计两个日期间的数据,你也可以穿件一个类,但是用struct更简单,同时帮你清理代码
require ‘ostruct‘
require ‘date‘
SelectOption = Struct.new(:from_date, :to_date) do
def filter_data(date)
return true if from_date< date && to_date > date
end
end
option_struct = SelectOption.new(Time.now, Time.now+10)
p option_struct.filter_data(Time.now+4)
类内部数据
class Person
Address = Struct.new(:street_1, :street_2, :city, :province, :country, :postal_code)
attr_accessor :name, :address
def initialize(name, opts)
@name = name
@address = Address.new(opts[:street_1], opts[:street_2], opts[:city], opts[:province], opts[:country], opts[:postal_code])
end
end
leigh = Person.new("Leigh Halliday", {
street_1: "123 Road",
city: "Toronto",
province: "Ontario",
country: "Canada",
postal_code: "M5E 0A3"
})
puts leigh.address.inspect
# <struct Person::Address street_1="123 Road", street_2=nil, city="Toronto", province="Ontario", country="Canada", postal_code="M5E 0A3">
作为测试使用的Stub
KCup = Struct.new(:size, :brewing_time, :brewing_temp)
colombian = KCup.new(:small, 60, 85)
brewer = Brewer.new(colombian)
expect(brewer.brew).to eq(true)
Struct相比较penstruct,速度快, 但是openStruct可以动态添加属性,
australia = OpenStruct.new(:country => "Australia", :population => 20_000_000)
australia.name=‘jack‘
p australia