support_amount_a = ProvinceMerchantChangeValue.find(:all, :select => "DISTINCT change_value_id", :conditions => ["status = 1 and merchant_id = ? and province_id =? and channel_id in (select id from channels where status = 1)", merchant_id, province_id]).map { |cv| cv.change_value_id }.compact
# Use ISO 8601 format for JSON serialized times and dates. ActiveSupport.use_standard_json_time_format = true
# Don‘t escape HTML entities in JSON, leave that for the #json_escape helper. # if you‘re including raw json in an HTML page. ActiveSupport.escape_html_entities_in_json = false
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 因为obj对象没法响应talk这个消息,如果使用 respond_to? 这个方法,就可以实现判断对象能否响应给定的消息了 obj = Object.new ifobj.respond_to?("talk") obj.talk else puts"Sorry,
object can‘t talk!" end request = gets.chomp if book.respond_to?(request) puts book.send(request) else puts"Input
error" end
22.method_missing,一个 Ruby 程序员的梦中情人
def method_missing(method, *args) if method.to_s =~ /(.*)_with_cent$/ attr_name = $1 if self.respond_to?(attr_name) ‘%.2f‘ % (self.send(attr_name).to_f / 100.00) else super end end end
http://ruby-china.org/topics/3434
23.chomp
chomp方法是移除字符串尾部的分离符,例如\n,\r等...而gets默认的分离符是\n
24. hash.each_pair{|k,v|} & send()
if bank_order.present? data_hash.each_pair { |k, v| bank_order.send("#{k}=", v) } else bank_order = BankOrder.new data_hash end