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

          Ruby 學習筆記 (2)

          Posted on 2007-06-16 19:30 ZelluX 閱讀(293) 評論(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)的很多程序都是依循測試驅動開發(fā)的思想寫出來的,測試單元中的方法通常有兩種目的。
          一種是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"

          主站蜘蛛池模板: 吉安县| 吉林省| 桐庐县| 师宗县| 榕江县| 宁都县| 东乌| 北流市| 探索| 乾安县| 佛冈县| 景宁| 沾化县| 红原县| 鄯善县| 锡林浩特市| 唐海县| 深州市| 连江县| 龙江县| 长乐市| 乾安县| 平舆县| 平潭县| 博客| 遵义市| 缙云县| 崇礼县| 黔西县| 赣榆县| 若尔盖县| 汕尾市| 土默特右旗| 大港区| 崇左市| 阿城市| 汉源县| 广河县| 逊克县| 于都县| 廉江市|