zoukankan      html  css  js  c++  java
  • ruby 使用Struct场景

    替代类使用,节省代码,清晰简洁

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

  • 相关阅读:
    C语言 · 递归求二项式系数值
    C语言 · 错误票据
    C语言 · 色盲的民主
    C语言 · 分苹果
    C语言 · Quadratic Equation
    C语言 · 企业奖金发放
    C语言 · 最长单词
    C语言 · 高精度加法
    C语言 · 判断回文
    C语言 · 简单计算器
  • 原文地址:https://www.cnblogs.com/or2-/p/5495538.html
Copyright © 2011-2022 走看看