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

          Ruby 學(xué)習(xí)筆記 (2)

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

          1. Array#reject 方法遍歷一個(gè)集合的每個(gè)元素,并把符合條件的元素刪去。
          例如去掉數(shù)組中的所有素?cái)?shù)
          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. 判斷是否在命令行運(yùn)行腳本
          if $0 == __FILE__
          check_usage
          compare_inventory_files(ARGV[0], ARGV[1])
          end
          類似于Java類的main方法,在被其他類導(dǎo)入時(shí)不會(huì)運(yùn)行其中的代碼。

          4. Enumerable#any? 方法查找一個(gè)集合中是否有滿足條件的元素
          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. 關(guān)于測(cè)試
          這本書(Everyday Scripting with Ruby)的很多程序都是依循測(cè)試驅(qū)動(dòng)開(kāi)發(fā)的思想寫出來(lái)的,測(cè)試單元中的方法通常有兩種目的。
          一種是direct test,需要測(cè)試那個(gè)函數(shù)就直接調(diào)用那個(gè)函數(shù),傳遞的參數(shù)都是直接寫出來(lái)的。
          另一種是bootstrapping test,被測(cè)試函數(shù)的參數(shù)也是通過(guò)生成這些參數(shù)的函數(shù)生成的,即一個(gè)方法測(cè)試了多個(gè)對(duì)象。
          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"

          主站蜘蛛池模板: 雅安市| 泰顺县| 波密县| 玉溪市| 赤壁市| 长垣县| 江津市| 井冈山市| 靖远县| 东丽区| 三河市| 积石山| 奉化市| 尖扎县| 都江堰市| 五华县| 收藏| 灵山县| 精河县| 余姚市| 紫阳县| 浦城县| 佛坪县| 蒙城县| 子长县| 邯郸县| 仪征市| 武冈市| 眉山市| 威远县| 普安县| 凉山| 平陆县| 阜新市| 收藏| 红河县| 上饶县| 沙河市| 怀集县| 茌平县| 视频|