Wednesday, 12 October 2011

Note FOR Ruby 1.9 (2)

10.Ruby之Array,Hash,Set,Matrix/Vector:
  • Array:
  • 创建一个Array:
    arr = Array.new(3, "baron")
    for i in arr
         print " " << i
    end

    Array比较<=>:
    小于返回-1,等于返回0,大于返回1
    改写比较方式,可以使用<, ==, >进行比较:
    class MyArray < Array
         include Comparable

         def <=>(anotherArray)
             self.length <=> anotherArray.length
         end
    end

    myarr1 = MyArray.new([0, "ab", "c"])
    myarr2 = MyArray.new([1, 2])

    p myarr1 <=> myarr2

    Array.sort:
    arr2 = ["one", "b", "abcde", 1, 3]
    sort_arr2 = arr2.sort {
         |a, b|
         a.to_s <=> b.to_s
    }
    p sort_arr2

    Array运算:
    1. &: 交
    2. +: 并
    3. -: 差
    4. <<: 添加
    Array.flatten:
    arr = [1, 2, 3, [4, 5]]
    p arr.flatten

  • Hash:
  • 创建Hash:
    hash = Hash.new("Default")
    hash['b'] = "ccc"
    p hash
    p hash.default

    Hash.sort:
    用法和Array类似
11.Ruby之循环
  • for ... in ... do
    end
  • ... .each do |...|
    end
  • while ... do
    end
  • begin
    end while ...
  • until ... do
    end
  • begin
    end until ...
  • loop {
    }
12.Ruby之条件
  • 条件运算符,Ruby有两套,而且优先级不同,最好不要混用
    1. and, or, not
    2. &&, ||, !
    3. === 相当于 include?
  • if ... then ... elsif ... then ... else ... end
  • begin ... end if ...
  • begin ... end unless ...
  • case ... when ... else ... end
    case返回值为when的最后一条语句
  • catch,throw:
    catch (Symbol) {
    ...
    throw Symbol
    ...
    }
13.Ruby之Enumerable:
Ruby中的Array已经包括Enumerable模块,其中包含了include?, collect, min, max方法:
arr = [1, 2, 3, 4, 5]
p arr.include?(3)
p arr.collect{ |i| i * i}
p arr.min
p arr.max

可以自定义min, max的行为:
hash = {"one" => "Monday", "two" => "Tuesday"}
p hash.min{|a, b| a[1].length <=> b[1].length}

each, yield用法
class MyCollection
     include Enumerable

     def initialize(someItems)
         @items = someItems
     end

     def each
         @items.each { |i| yield(i) }
     end
end

things = MyCollection.new(['x', 'yz', 'defgh', 'ij', 'klmno'])
p things.min
p things.max
p things.collect{ |i| i.upcase }
当调用min,max,collect等方法时,其会调用each方法

No comments :

Post a Comment