第十五章 通用扩展
这章就是要记住的很多函数,必然都是经常用到的,总不能写程序时经常查参考吧?那样容易打断逻辑思路的!!所以要考验一下记忆力了。注:这里介绍的都是rails的函数,ruby的另外参考
Let's rock
所有的ruby对象(下面用for_all代替):
--to_json
--to_yaml
ActiveRecord对象/hash对象:
--to_xml
for_all:
--blank?
Enumerable:
--group_by 如同对Enumerable进行SQL上的group by 一样,返回一个hash
比如:
myHouse =House.group_by(|h|h.usage)
就可以用myHouse[:住宅]访问
Enumerable(注:如未声明,则下列方法都适用于该类):
--index_by 没搞懂,待实验
--sum
例:
all_amount =Loan.find(:all).sum(|l|.loan_amount)
String:
--str.at(2) 返回第2个字符
--str.from(8) 从第8个字符到末尾 str.last(8)
--str.to(8) 从开头到第8个字符 str.frist(8)
--str.first 第一个字符
--str.last 最后一个字符
--str.start_with?("no'') 是否以no开头 区分大小写
--str.ends_with?("no")
--str.each_char{|ch|inverse = str+inverse} 可以将字符串颠倒
--str.pluralize 复数
--str.singlularize 单数
在environment.rb中,可以对inflector模块进行配置,配置自己的单复数规则
前者定义以goose结尾的复数形式为geese
后者定义括号中的单词,单复数一样
容量类函数(以字节计数):
--20.bytes 返回“20字节”的字节数
--20.kilobytes
--20.megabytes
--20.gigabytes
--20.terabytes
--20.petabytes
日期段类函数(以秒计数):
--20.years 按每年365天算总共多少秒
--20.months 按每月30天算
--20.days
--20.weeks
--20.hours
--20.seconds
time类函数,返回time
--20.days.from_now 现在起20天后
--20.days.ago 20天前
--Time.now
--20.minutes.since("2009-1-1 00:00:00''.to_time)
--20.minutes.until("2009-1-1 00:00:00''.to_time)
更酷的日期时间类函数
now = Time.now
now.to_date
now.to_s
now.to_s(:short) 去掉星期、年份、秒
now.ago(3600) 3600秒之前的时间(注意和上一个ago的区别,前者是时间段.ago(某时间),后者是时间.ago(某时间段)
now.at_beginning_of_month 本月第一天
now.at_beginning_of_week
now.change(:hour=>13) 把小时改成13
now.last_month 后退一个月 这个应该比1.months.until(now),要精确,前者是减30天
now.last_year
now.month_ago(2)
now.month_since(2)
now.tomorrow
now.yesterday
now.advance(:days=>30) 30天后,晕,有了这个,其他相对函数不用记了嘛。汗。。。
Time.days_in_month(2,2000) 2000年2月的天数
date.to_s(:db) 数据库可读模式
创建自己个日期格式
any_date.to_s(:myformat) ,其中的myformat在environment.rb中定义
:myformat =>"%y-%m-%d"
p251