ruby 使用Struct情境

來源:互聯網
上載者:User

標籤:

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

使用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

ruby 使用Struct情境

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.