Chinaunix首页 | 论坛 | 博客
  • 博客访问: 473628
  • 博文数量: 112
  • 博客积分: 5696
  • 博客等级: 大校
  • 技术积分: 1720
  • 用 户 组: 普通用户
  • 注册时间: 2007-08-17 09:58
文章分类

全部博文(112)

文章存档

2011年(22)

2010年(28)

2009年(21)

2008年(41)

分类: Python/Ruby

2011-11-05 11:32:54

ActiveSppourt 是一组类库,是所有rails组建可以共享的

Rails 对所有Ruby对象进行了扩展 to_json() ,to_yaml()

Rating = Struct.new(:name,:ratings)
rating = Rating.new("Rails",[10,10,9.5,10])

puts rating.to_json  输出 ["Rails",[10,10,9.5,10]]
puts tating.to_yaml 输出 name:Rails
     rating:
- 10
- 10
- 9.5
- 10

所有的ActiveRecord 对象及所有hash都提供了 to_xml()方法

Rails还增加了.blank? 方法
----nil 和 false 对象,  返回true
----数值和true对象,  返回false
----其他对象,只有当对象为空时,返回true


枚举和数组
Rails 给 Ruby的Enumerable类型加上一些魔法

group_by()

groups = posts.group_by(|post| post.author_id)

Rails还给 Enumerable上另外2个方法 index_by(),将一个集合作为参数,并将其转换为一个hash,其中的值来源自集合,而键则是各个元素经过代码块后的返回值
us_states = State.find(:all)
state_lookup = us_states.index_by{|State| state.short_name}

sum 可以求和
total_orders = Oder.find(:all).sum{|order| order.value}
阅读(2904) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~