Java是仙人指,Ruby是飘得一剑------RubyExample

001 $KCODE = 'e' 002 #--------------------------- begin here ---" 003 puts "--------------------------- begin here ---" 004 005 6 . times { | i | p i } 006 print 4 * Math . atan2 ( 1 , 1 ), " /n " 007 #while gets() 008 #    print if /From / 009 #end 010 011 #--------------------------- everything is a class --- 012 puts "--------------------------- everything is a class ---" 013 print "aaa /n bbb /n " 014 print 'aaa/nbbb' 015 print " /n " 016 %w(cat dog horse) . each { | name | print name , " /n " } 017 5 . times { print "*" } 018 3 . upto ( 6 ) { | i | print i } 019 ( 'a' . . 'e' ) . each { | char | print char } 020 puts 021 022 #--------------------------- class and inspect --- 023 puts "--------------------------- class and inspect ---" 024 class Song 025     def initialize ( name , artist , duration ) 026         @name = name 027         @artist = artist 028         @duration = duration 029     end 030 end 031 song = Song . new ( "Bob" , "Tom" , 20 ) 032 puts song . inspect 033 puts song . to_s 034 035 #--------------------------- override to_s --- 036 puts "--------------------------- override to_s ---" 037 class Song 038     def to_s 039         "Song: #@name #@artist ( #@duration )" 040     end 041 end 042 puts song . to_s 043 044 #--------------------------- read attribuite --- 045 puts "--------------------------- read attribuite ---" 046 class Song 047     attr_reader :name , :artist , :duration 048 end 049 puts "song.name     = " + song . name 050 puts "song.artist   = " + song . artist 051 puts "song.duration = " + song . duration . to_s 052 053 #--------------------------- write attribuite --- 054 puts "--------------------------- write attribuite ---" 055 class Song 056     attr_writer :duration 057     def name = ( new_name ) 058         @name = new_name 059     end 060 end 061 song = Song . new ( "Bicylops" , "Fleck" , 260 ) 062 song . duration = 257 063 song . name = "IamNewName" 064 puts "song.duration = " + song . duration . to_s 065 puts "song.name     = " + song . name 066 067 #--------------------------- virtual attribute --- 068 puts "--------------------------- virtual attribute ---" 069 class Song 070     def duration_in_minutes 071         @duration / 60 . 0 # force floating point 072     end 073     def duration_in_minutes = ( new_duration ) 074         @duration = ( new_duration * 60 ) . to_i 075     end 076 end 077 song = Song . new ( "Bicylops" , "Fleck" , 260 ) 078 puts "song.duration_in_minutes = " + song . duration_in_minutes . to_s 079 song . duration_in_minutes = 5 080 puts "song.duration = " + song . duration . to_s 081 082 #--------------------------- Singleton --- 083 puts "--------------------------- Singleton ---" 084 class MyLogger 085     private_class_method :new 086     @@logger = nil 087     def MyLogger . create 088         @@logger = new unless @@logger 089         @@logger 090     end 091 end 092 093 #--------------------------- access control --- 094 puts "--------------------------- access control ---" 095 class Accounts 096     def initialize ( checking , savings ) 097         @checking = checking 098         @savings = savings 099     end 100 101     private 102     def debit ( account , amount ) 103         account . balance -= amount 104     end 105     def credit ( account , amount ) 106         account . balance += amount 107     end 108 109     public 110     #... 111     def transfer_to_savings ( amount ) 112         debit ( @checking , amount ) 113         credit ( @savings , amount ) 114     end 115     #... 116 end 117 118 #--------------------------- array --- 119 puts "--------------------------- array ---" 120 a = [ 1 , 3 , 5 , 7 , 9 ] 121 print a [ 0 ] , " " , a [- 1 ] , " /n " 122 print a [- 3 , 4 ] , " /n " 123 print a [- 3 . . - 1 ] , " /n " 124 125 #--------------------------- hash --- 126 puts "--------------------------- hash ---" 127 h = { 'dog' => 'canine' , 'cat' => 'feline' , 'donkey' => 'asinine' } 128 print h [ 'dog' ] , " " , h [ 0 ] , " /n " 129 130 #--------------------------- unit testing --- 131 class SongList 132     def initialize 133         @songs = Array . new 134     end 135 136     def append ( song ) 137         @songs . push ( song ) 138         self 139     end 140 141     def delete_first 142         @songs . shift 143     end 144 145     def delete_last 146         @songs . pop 147     end 148 149     def [] ( index ) 150         @songs [ index ] 151     end 152 153     def with_title ( title ) 154         @songs . find { | song | title == song . name } 155     end 156 157 end 158 159 require 'test/unit' 160 class TestSongList < Test :: Unit :: TestCase 161     def test_delete 162         puts "--------------------------- unit testing ---" 163         list = SongList . new 164         s1 = Song . new ( 'title1' , 'artist1' , 1 ) 165         s2 = Song . new ( 'title2' , 'artist2' , 2 ) 166         s3 = Song . new ( 'title3' , 'artist3' , 3 ) 167         s4 = Song . new ( 'title4' , 'artist4' , 4 ) 168         list . append ( s1 ) . append ( s2 ) . append ( s3 ) . append ( s4 ) 169         assert_equal ( s1 , list [ 0 ] ) 170         assert_equal ( s3 , list [ 2 ] ) 171         assert_nil ( list [ 9 ] ) 172         assert_equal ( s1 , list . delete_first ) 173         assert_equal ( s2 , list . delete_first ) 174         assert_equal ( s4 , list . delete_last ) 175         assert_equal ( s3 , list . delete_last ) 176         assert_nil ( list . delete_last ) 177     end 178 end 179 180 #--------------------------- iterators --- 181 puts "--------------------------- iterators ---" 182 [ 4 , 5 , ]. each { | i | puts i * i } 183 puts [ "H" , "A" , "L" ]. collect { | x | x . succ } 184 puts "inject sum = " + [ 1 , 3 , 5 , 7 ]. inject ( 0 ) { | sum , element | sum + element } . to_s 185 puts "inject product = " + [ 1 , 3 , 5 , 7 ]. inject ( 1 ) { | product , element | product * element } . to_s 186 187 #--------------------------- closure --- 188 puts "--------------------------- closure ---" 189 songlist = SongList . new 190 class Button 191     def initialize ( label ) 192         @label = label 193     end 194 end 195 class JukeboxButton < Button 196     def initialize ( label , & action ) 197         super ( label ) 198         @action = action 199     end 200     def button_pressed 201         @action . call ( self ) 202     end 203 end 204 start_button = JukeboxButton . new ( "Start" ) { songlist . start } 205 pause_button = JukeboxButton . new ( "Pause" ) { songlist . pause } 206 207 #--------------------------- lambda --- 208 puts "--------------------------- lambda ---" 209 def n_times ( thing ) 210     return lambda { | n | thing * n } 211 end 212 p1 = n_times ( 23 ) 213 puts p1 . call ( 3 ) 214 puts p1 . call ( 4 ) 215 puts p2 = n_times ( "Hello " ) 216 puts p2 . call ( 3 ) 217 218 #--------------------------- numbers --- 219 puts "--------------------------- numbers ---" 220 num = 3 221 9 . times do 222     puts " #{ num . class } : #{ num } " 223     num *= num 224 end 225 226 3 . times { print "X " } 227 1 . upto ( 5 ) { | i | print i , " " } 228 99 . downto ( 95 ) { | i | print i , " " } 229 50 . step ( 80 , 5 ) { | i | print i , " " } 230 print " /n " 231 232 somelines = "1 2 /n 3 4 /n 5 6" 233 somelines . each do | line | 234     v1 , v2 = line . split # split line on spaces 235     print v1 + v2 , " " 236 end 237 puts 238 239 somelines . each do | line | 240     v1 , v2 = line . split 241     print Integer ( v1 ) + Integer ( v2 ), " " 242 end 243 puts 244 245 #--------------------------- string --- 246 puts "--------------------------- string ---" 247 puts 'escape using "//"' 248 puts 'That/'s right' 249 puts "Seconds/day: #{ 24 * 60 * 60 } " 250 puts " #{ 'Ho! ' * 3 } Merry Christmas!" 251 puts "This is line #$." 252 puts "now is #{ def the ( a ) 253                     'the ' + a 254                 end 255                 the ( 'time' ) 256               } for all good coders..." 257 258 print << END_OF_STRING 259     The body of the string 260     is the input lines up to 261     one ending with the same 262     text that followed the '<<' 263 END_OF_STRING 264 265 print <<- STRING1 , <<- STRING2 266         Concat 267         STRING1 268             enate 269             STRING2 270 271 #--------------------------- string operation --- 272 puts "--------------------------- string operation ---" 273 File . open ( "songdata.txt" , "r" ) do | song_file | 274     songs = SongList . new 275     song_file . each do | line | 276         file , length , name , title = line . chomp . split ( //s*/|/s*/ ) 277         if ! ( file && length && name && title ) 278             next 279         end 280 281         name . squeeze! ( " " ) 282         mins , secs = length . scan ( //d+/ ) 283         songs . append ( Song . new ( title , name , mins . to_i * 60 + secs . to_i )) 284     end 285     puts songs [ 1 ] 286 end 287 288 #--------------------------- range --- 289 puts "--------------------------- range ---" 290 class VU 291     include Comparable 292     attr :volume 293     def initialize ( volume ) # 0..9 294         @volume = volume 295     end 296 297     def to_s 298         inspect 299     end 300 301     def inspect 302         '#' * @volume 303     end 304 305     # Support for ranges 306     def <=> ( other ) 307         self . volume <=> other . volume 308     end 309 310     def succ 311         raise ( IndexError , "Volume too big" ) if @volume >= 9 312         VU . new ( @volume . succ ) 313     end 314 end 315 316 medium_volume = VU . new ( 4 ) . . VU . new ( 7 ) 317 puts medium_volume . to_a 318 medium_volume . include? ( VU . new ( 3 )) 319 320 #--------------------------- regex --- 321 puts "--------------------------- regex ---" 322 def show_regexp ( a , re ) 323     if a =~ re 324         " #{ $` } << #{ $& } >> #{ $' } " 325     else 326         "no match" 327     end 328 end 329 puts show_regexp ( 'very interesting' , /t/ ) 330 puts show_regexp ( 'Fats Waller' , /a/ ) 331 puts show_regexp ( 'Fats Waller' , /ll/ ) 332 puts show_regexp ( 'Fats Waller' , /z/ ) 333 puts show_regexp ( "this is /n the time" , /^the/ ) 334 puts show_regexp ( "this is /n the time" , /is$/ ) 335 puts show_regexp ( "this is /n the time" , //Athis/ ) 336 puts show_regexp ( "this is /n the time" , //Athe/ ) 337 puts show_regexp ( "this is /n the time" , //bis/ ) 338 puts show_regexp ( "this is /n the time" , //Bis/ ) 339 340 a = 'see [Design Patterns page 123]' 341 puts show_regexp ( a , /[]]/ ) 342 puts show_regexp ( a , /[-]/ ) 343 puts show_regexp ( a , /[^a-z]/ ) 344 puts show_regexp ( a , /[^a-z/s]/ ) 345 346 def mixed_case ( name ) 347     name . gsub ( //b/w/ ) { | first | first . upcase } 348 end 349 puts mixed_case ( "fats waller" ) 350 puts mixed_case ( "louis armstrong" ) 351 puts mixed_case ( "strength in numbers" ) 352 353 puts "fred:smith" . sub ( /(/w+):(/w+)/ , '/2, /1' ) 354 puts "nercpyitno" . gsub ( /(.)(.)/ , '/2/1' ) 355 #Additional backslash sequences work in substitution strings: 356 #   /& (last match) 357 #   /+ (last matched group) 358 #   /` (string prior to match) 359 #   /' (string after match) 360 #   // (a literal backslash). 361 str = 'a/b/c' #"a/b/c" 362 puts str . gsub ( , '') #"a//b//c" 363 puts str.gsub(/ // / ) { '' } # "a//b//c" 364 puts str . gsub ( , '/&/&') #"a//b//c" 365 366 367 def unescapeHTML(string) 368     str = string.dup 369     str.gsub!(/ & ( . * ?) ; / n ) { 370         match = $1 . dup 371         case match 372             when //Aamp/z/ni then '&' 373             when //Aquot/z/ni then '"' 374             when //Agt/z/ni then '>' 375             when //Alt/z/ni then '<' 376             when //A#(/d+)/z/n then Integer ( $1 ) . chr 377             when //A#x([09af]+)/z/ni then $1 . hex . chr 378         end 379     } 380     str 381 end 382 puts unescapeHTML ( "1&lt;2 &amp;&amp; 4&gt;3" ) 383 puts unescapeHTML ( "&quot;A&quot; = &#65; = &#x41;" ) 384 385 #--------------------------- method --- 386 puts "--------------------------- method ---" 387 class TaxCalculator 388     def initialize ( name , & block ) 389         @name , @block = name , block 390     end 391     def get_tax ( amount ) 392         " #@name on #{ amount } = #{ @block . call ( amount ) } " 393     end 394 end 395 tc = TaxCalculator . new ( "Sales tax" ) { | amt | amt * 0 . 075 } 396 puts tc . get_tax ( 100 ) 397 puts tc . get_tax ( 250 ) 398 399 def meth_one 400     "one" 401 end 402 puts meth_one 403 def meth_two ( arg ) 404     case 405     when arg > 0 406         "positive" 407     when arg < 0 408         "negative" 409     else 410         "zero" 411     end 412 end 413 puts meth_two ( 23 ) 414 puts meth_two ( 0 ) 415 416 def meth_three 417     100 . times do | num | 418         square = num * num 419         return num , square if square > 1000 420     end 421 end 422 puts meth_three 423 424 425 #--------------------------- lambda --- 426 puts "--------------------------- lambda ---" 427 print "(t)imes or (p)lus: " 428 times = "plus" 429 print "number: " 430 number = Integer ( "100" ) 431 if times =~ /^t/ 432     puts (( 1 . . 10 ) . collect { | n | n * number } . join ( ", " )) 433 else 434     puts (( 1 . . 10 ) . collect { | n | n + number } . join ( ", " )) 435 end 436 437 puts "lambda version" 438 print "(t)imes or (p)lus: " 439 times = "times" 440 print "number: " 441 number = Integer ( "3" ) 442 if times =~ /^t/ 443     calc = lambda { | n | n * number } 444 else 445     calc = lambda { | n | n + number } 446 end 447 puts (( 1 . . 10 ) . collect ( & calc ) . join ( ", " )) 448 449 450 #--------------------------- o.method --- 451 puts "--------------------------- o.method ---" 452 453 plus = 1 . method ( :+ ) 454 puts plus . call ( 2 )      # => 3 (1+2) 455 456 #--------------------------- string operations --- 457 puts "--------------------------- string operations ---" 458 puts "123456789" . count ( "2378" )          # => 4 459 puts "123456789" . count ( "2-8" , "^4-6" )   # => 4 460 print "123 /n " . chomp 461 puts " 123" . chop 462 puts " abc" * 8 463 puts "bar" [ 1 . . 2 ]    # => "ar" 464 puts "bar" [ 1 . . - 1 ]   # => "ar" 465 puts "bar" [- 2 . . 2 ]   # => "ar" 466 puts "bar" [- 2 . . - 1 ] # => "ar" 467 puts "bar" [ 1 , 2 ]     # => "ar" 468 puts "bar" [- 1 , 1 ]   # => "r" 469 puts "0x%x" % 13 470 puts "123456789" . delete ( "2378" )            # =>"14569" 471 puts "123456789" . delete ( "2-8" , "^4-6" )     # =>"14569" 472 puts "aBC" . capitalize 473 puts "aBC" . upcase 474 puts "aBC" . downcase 475 puts "aBC" . swapcase 476 puts "iloveyuchi" . sub ( /[aeiou]/ , "." ) 477 puts "iloveyuchi" . gsub ( /[aeiou]/ , "." ) 478 puts "123abc" . hex 479 puts "123abc" . index ( "b" ) 480 puts "123abc" . include? ( "b" ) 481 puts "aa" . succ                # => "ab" 482 puts "99" . succ                # => "100" 483 puts "a9" . succ                # => "b0" 484 puts "Az" . succ                # => "Ba" 485 puts "zz" . succ                # => "aaa" 486 puts "foobarbaz" . scan ( /(ba)(.)/ )   # => [["ba", "r"], ["ba", "z"]] 487 "foobarbaz" . scan ( /(ba)(.)/ ) { | s | p s } 488 a = "0123456789" 489 p a . slice! ( 1 , 2 )          # "12" 490 p a                      # "03456789" 491 p "a b c" . split             # => ["a","b","c"] 492 p "a:b:c" . split ( /:/ )        # => ["a","b","c"] 493 p "a:b:c:::" . split ( /:/ , 4 )   # => ["a","b","c","",":"] 494 p "a:b:c::" . split ( /:/ , - 1 )   # => ["a","b","c","",""] 495 p "abc" . split ( // )           # => ["a","b","c"] 496 puts "112233445" . squeeze         # =>"12345" 497 puts "112233445" . squeeze ( "1-3" ) # =>"123445" 498 puts "abc" + "   abc   " . strip + "abc" 499 puts "foo" . tr_s ( "o" , "f" )              # => "ff" 500 puts "foo" . tr ( "o" , "f" ) . squeeze ( "f" )   # => "f" 501 puts "foo" . sub ( /fo/ , "dem" ) 502 "a" . upto ( "ba" ) { | x | print " #{ x } " } # prints a, b, c, ... z,aa, ... az, ba 503 puts 504 =begin 505 these 506     are 507         comments 508 =end 509 510 puts << OOO 511 here we are 512 inline 513 strings 514 OOO 515 516 #--------------------------- exception --- 517 puts "--------------------------- exception ---" 518 count = 0 519 begin 520     count += 1 521     f = File . open ( "testfile" ) 522     # .. process 523 rescue 524     # .. handle error 525     puts "Got error!" 526     retry if f . nil? && ( count < 3 ) 527 else 528     puts "Congratulations, no errors!" 529 ensure 530     puts "Ensure file is closed!" 531     f . close unless f . nil? 532 end 533 534 class RetryException < RuntimeError 535     attr_reader :ok_to_retry 536     attr_writer :ok_to_retry 537     def initialize ( ok_to_retry ) 538         @ok_to_retry = ok_to_retry 539     end 540 end 541 542 $flag = false 543 def read_data ( socket ) 544     #data = socket.read(512) 545     data = nil 546     if data . nil? 547         raise RetryException . new ( $flag ), "transient read error" 548     end 549     # .. normal processing 550 end 551 552 begin 553     $flag = ! $flag 554     #stuff = read_data(socket) 555 #    stuff = read_data("") 556     # .. process stuff 557 rescue RetryException => detail 558     if detail . ok_to_retry 559         puts "Oh yeah, we got exception, let's try again" 560         retry 561     else 562         puts "Oh shit, I give up" 563         raise 564     end 565 end 566 567 #--------------------------- array operations --- 568 puts "--------------------------- array operations ---" 569 puts ( [ 1 , 3 , 5 ]&[ 1 , 2 , 3 ] ) . inspect 570 puts ( [ 1 , 3 , 5 ]|[ 1 , 2 , 3 ] ) . inspect 571 puts ( [ 1 , 3 , 5 ]* 3 ) . inspect 572 puts [ "foo" , "bar" ] * "-"      # => "foo-bar" 573 puts ( [ 1 , 3 , 5 ] - [ 1 , 2 , 3 ] ) . inspect 574 puts ( [ 1 , 3 , 5 ] + [ 1 , 2 , 3 ] ) . inspect 575 puts ( [ 1 , 3 , 5 ] << [ 4 , 6 ] ) . inspect 576 577 arr = [ 0 , 1 , 2 , 3 , 4 , 5 ] 578 arr [ 0 . . 2 ] = [ "a" , "b" ]      # arr => ["a", "b", 3, 4, 5] 579 puts arr . inspect 580 puts arr [ 1 , 0 ] = [ "c" ]           # arr => ["a", "c", "b", 3, 4, 5] 581 puts arr . inspect 582 583 #arr.assoc( key) 584 #Searches through an array of arrays, returning the first array with an initial element matching key. 585 a = [[ 1 , 2 ] , [ 2 , 4 ] , [ 3 , 6 ]] 586 puts a . assoc ( 2 ) . inspect                   # => [2, 4] 587 588 a . clear 589 puts a . inspect 590 591 puts [ 1 , 2 , 3 ]. collect { | x | x * 2 } . inspect     # => [2,4,6]. 592 593 a = [ 5 , 6 , 7 , 8 , 9 ] 594 a . each_index { | i | puts "a[ #{ i } ]=" + a [ i ]. to_s } 595 a . each_with_index { | x , i | puts "a[ #{ i } ]= #{ x } " } 596 597 a = [ 1 , 2 , 3 , 3 , 4 , 5 , 4 ] 598 puts a . inspect 599 a . uniq! 600 puts a . inspect 601 602 puts [ 1 , [ 2 , 3 , [ 4 ] , 5 ]]. flatten . inspect    #=> [1, 2, 3, 4, 5] 603 604 puts [ "hello" , "world" ]. join ( " " ) . inspect   #=> "hello world" 605 606 a = [ 1 , 2 , 3 ] 607 a . unshift ( 0 )       #=> [0,1,2,3] 608 609 #--------------------------- enumerable --- 610 puts "--------------------------- enumerable ---" 611 #Enumerable Enumerable mix-in module  612 #  The Enumerable module assumes that the including class has an each method. 613 #  You can add the following methods to a class that provides each, by just including this module. 614 puts [ "foo" , "bar" , "baz" ]. find { | s | /^b/ =~ s } # => "bar" 615 puts [ "foo" , "bar" , "baz" ]. detect { | s | /^b/ =~ s } # => "bar" 616 puts [ "foo" , "bar" , "baz" ]. select { | s | /^b/ =~ s } # => ["bar","baz"] 617 puts [ "foo" , "bar" , "baz" ]. grep ( /^b/ )   # => ["bar","baz"] 618 puts [ 1 , "bar" , 4 . 5 ]. grep ( Numeric )      # => [1,4.5] 619 puts [ 1 , "bar" , 4 . 5 ]. grep ( Numeric ) { | x | puts x + 1 } 620 621 622 puts "--------------------------- end of samples"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值