Alternative class use, save code, clear and concise
Using struct
Selectoption = Struct.new (:d isplay,: 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]
Using classes
Class Selectoption
Attr_accessor:d isplay,: 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]
Temporary data structures
For example, an example that uses two dates to filter form data, you can use two values in a filtered place, or you can create a filterrange struct structure that has a from_date and to_date attribute, and you might need a way to count the data for two days , you can also wear a class, but it's easier to use a struct and help you clean up the code
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 internal data
Class Person
Address = Struct.new (: street_1,: street_2,: City,:p rovince,: Country,:p Ostal_code)
Attr_accessor:name,: Address
Def initialize (name, opts)
@name = Name
@address = Address.new (opts[:street_1], opts[:street_2], opts[:city], opts[:p rovince], opts[:country], opts[:p Ostal_ 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" >
The stub used as a test
Kcup = struct.new (: Size,: Brewing_time,: Brewing_temp)
Colombian = kcup.new (: Small, 60, 85)
Brewer = Brewer.new (Colombian)
Expect (brewer.brew). To EQ (true)
Structs Compare penstruct, fast, but openstruct can add properties dynamically,
Australia = openstruct.new (: Country = "Australia",:p opulation = 20_000_000)
Australia.name= ' Jack '
P Australia
Ruby uses a struct scene