ruby 使用Struct場景

c3tc3tc3t發表於2016-05-15

替代類使用,節省程式碼,清晰簡潔

使用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 date>=from_date..date<=to_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

相關文章