posts - 403, comments - 310, trackbacks - 0, articles - 7
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          Ruby 學習筆記 (2)

          Posted on 2007-06-16 19:30 ZelluX 閱讀(288) 評論(0)  編輯  收藏 所屬分類: Scripting

          1. Array#reject 方法遍歷一個集合的每個元素,并把符合條件的元素刪去。
          例如去掉數組中的所有素數
          nums = nums.reject do | num |
          prime?(num)
          end
          puts nums

          2. String#chomp 方法
          str.chomp(separator=$/) => new_str
          Returns a new +String+ with the given record separator removed from
          the end of _str_ (if present). If +$/+ has not been changed from
          the default Ruby record separator, then +chomp+ also removes
          carriage return characters (that is it will remove +\n+, +\r+, and
          +\r\n+).

          "hello".chomp #=> "hello"
          "hello\n".chomp #=> "hello"
          "hello\r\n".chomp #=> "hello"
          "hello\n\r".chomp #=> "hello\n"
          "hello\r".chomp #=> "hello"
          "hello \n there".chomp #=> "hello \n there"
          "hello".chomp("llo") #=> "he"

          3. 判斷是否在命令行運行腳本
          if $0 == __FILE__
          check_usage
          compare_inventory_files(ARGV[0], ARGV[1])
          end
          類似于Java類的main方法,在被其他類導入時不會運行其中的代碼。

          4. Enumerable#any? 方法查找一個集合中是否有滿足條件的元素
          irb(main):004:0> deposits = [1, 0, 10000]
          irb(main):005:0> deposits.any? do | deposit |
          irb(main):006:1* deposit > 9999
          irb(main):007:1> end
          => true

          5. 關于測試
          這本書(Everyday Scripting with Ruby)的很多程序都是依循測試驅動開發的思想寫出來的,測試單元中的方法通常有兩種目的。
          一種是direct test,需要測試那個函數就直接調用那個函數,傳遞的參數都是直接寫出來的。
          另一種是bootstrapping test,被測試函數的參數也是通過生成這些參數的函數生成的,即一個方法測試了多個對象。
          Everyone finds their own balance between testing directly and testing indirectly. You will too.

          6. Time#strftime 方法
          t = Time.now
          t.strftime("Printed on %m/%d/%Y") #=> "Printed on 04/09/2003"
          t.strftime("at %I:%M%p") #=> "at 08:56AM"

          主站蜘蛛池模板: 隆子县| 肃南| 松阳县| 沅江市| 施秉县| 铜川市| 崇文区| 枞阳县| 修水县| 正镶白旗| 沈阳市| 故城县| 黄平县| 鄂尔多斯市| 浮山县| 高雄县| 台南县| 杭锦后旗| 毕节市| 南投县| 惠州市| 准格尔旗| 建始县| 谢通门县| 买车| 万安县| 东明县| 西畴县| 三原县| 绍兴县| 天台县| 枞阳县| 屏南县| 海阳市| 普兰店市| 西林县| 北宁市| 鄂温| 陆川县| 龙岩市| 永清县|