THE BOOK OF RUBY
288
A MatchData object may contain groups or ‘captures’ and these can be returned in an array using either the to_a or captures method, like this: matchdata.rb x = /(^.*)(#)(.*)/.match( 'def myMethod # This is a very nice method' ) x.captures.each{ |item| puts( item ) } The above displays: def myMethod # This is a very nice method
Note that there is a subtle difference between the captures and the to_a me-thods. The first returns only the captures: x.captures #=>["def myMethod ","#"," This is a very nice method"] The second returns the original string (at index 0) followed by the captures: x.to_a #=>["def myMethod # This is a very nice method","def myMethod ","#"," This is a very nice method"]
PRE AND POST MATCH
The MatchData class supplies the pre_match and post_match methods to return the strings preceding or following a match. Here, for example, we make a match on the comment character, ‘#’: pre_post_match.rb x = /#/.match( 'def myMethod # This is a very nice method' ) puts( x.pre_match ) #=> def myMethod puts( x.post_match ) #=> This is a very nice method
หนังสือของทับทิม
288
วัตถุ MatchData อาจมีกลุ่มหรือ 'จับ' และเหล่านี้จะสามารถกลับมาในอาเรย์โดยใช้ to_a หรือจับวิธีการเช่นนี้ matchdata.rb x = / (^. *) (#) ( . *) / การแข่งขัน ('def MyMethod # นี่คือวิธีการที่ดีมาก') x.captures.each {| รายการ | ทำให้ (รายการ)} แสดงด้านบน: def MyMethod # นี่คือวิธีการที่ดีมาก
ทราบว่ามี ความแตกต่างที่ลึกซึ้งระหว่างจับและ to_a ฉัน thods ผลตอบแทนที่แรกเท่านั้นจับ: x.captures # => ["def MyMethod", "#", "นี่เป็นวิธีที่ดีมาก"] ผลตอบแทนที่สองสายเดิม (ที่ดัชนี 0) ตามด้วยการจับ: x to_a # => ["def MyMethod # นี่คือวิธีการที่ดีมาก", "def MyMethod", "#", "นี่เป็นวิธีที่ดีมาก"]
ก่อนและหลังการแข่งขัน
ระดับ MatchData วัสดุ pre_match และวิธีการที่จะกลับ post_match สตริงก่อนหน้านี้ต่อไปหรือการแข่งขัน ที่นี่ตัวอย่างเช่นเราทำให้การแข่งขันในลักษณะแสดงความคิดเห็น, '#'. pre_post_match.rb x = / # / การแข่งขัน ('def MyMethod # นี่คือวิธีการที่ดีมาก') ทำให้ (x.pre_match) # => ทำให้ MyMethod def (x.post_match) # => นี่คือวิธีการที่ดีมาก
การแปล กรุณารอสักครู่..
