Ruby的25个编程细节(技巧、实用代码段)

2019-09-25 09:42:12于丽

    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet
    months = MONTH
    months = opts[:month].to_s.split(/,/) if opts[:month]

    fixed_row = months.collect{ |m| m.to_s + '月' }.insert(0, '')


    sheet1.row(0).concat(fixed_row)
    row1 = ['']
    (months.size - 1).times { row1 << ['用户数', '金额', '订单数'] }

    sheet1.row(1).concat(row1.flatten!)
    row = 2

    sheet1.row(row).insert(0, '全国')

    months.each_with_index do |m, i|
      sheet1.row(row).insert(i*3 + 1, self.monthly_users_count(m))
      sheet1.row(row).insert(i*3 + 2, self.monthly_amount(m))
      sheet1.row(row).insert(i*3 + 3, self.monthly_orders_count(m))    
    end

    PROVINCE.each do |province|
      row += 1
      sheet1.row(row).insert(0, province)
      months.each_with_index do |m, i|
        sheet1.row(row).insert(i*3 + 1, self.monthly_users_count_by_province(m, province))
        sheet1.row(row).insert(i*3 + 2, self.monthly_amount_by_province(m, province))
        sheet1.row(row).insert(i*3 + 3, self.monthly_orders_count_by_province(m, province))
      end  
    end

    path = "tmp/phone_recharge.xls"
    book.write path
    path
  end

17. inject({})

selected_conditions = base_conditions.inject({}) do |hash, data|
      hash[data.first] = data.last unless data.last.blank?
      hash
    end

18.time_str.instance_of?


return time_str if time_str.instance_of? Time

19.Person.instance_eval


Person.instance_eval do
    def species
      "Homo Sapien"
    end
  end

20.class_eval

class Foo
  end
  metaclass = (class << Foo; self; end)
  metaclass.class_eval do
      def species
        "Homo Sapien"
      end
    end
  end


21.Ruby中 respond_to? 和 send 的用法
http://galeki.is-programmer.com/posts/183.html