道喜技术日记 .^. 天天红玉世界

Rails Ruby MacOSX 。。。创新来自于刻苦的实践和勤奋的思考... www.hhtong.com


Ruby世界:如何把Hash对象键的字符串类型变成为符号类型

Gudao Luo2011-03-10 at 22:23发表的

2011-03-10-2144-str2sym-hash
  • 说明
    • 下面参考资料(1)的代码有些错误。

Ruby代码世界:Array排序代码实例

Gudao Luo2009-09-06 at 10:33发表的

2009-09-06 1515

以字符串为元素的Array排序代码清单一
   items = [ "d", "a", "e", "c", "b" ]
items.sort #从小到大排序,=> ["a", "b", "c", "d", "e"]
items.sort {|x,y| x <=> y } #从小到大排序,=> ["a", "b", "c", "d", "e"]
items.sort {|x,y| y <=> x } #从大到小排序, => ["e", "d", "c", "b", "a"]
以模型对象为元素的Array排序代码清单二
class Company
attr_accessor :nr
attr_accessor :name
def initialize(nr, name)
@nr = nr
@name = name
end
end
objects = [Company.new(2, "d"), Company.new(1, "a"), Company.new(3, "e")]
objects.sort {|x,y| x.name <=> y.name }
#以模型对象元素name进行模型对象的排序结果:
#=> objects = [Company.new(1, "a"), Company.new(2, "d"), Company.new(3, "e")]