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

来源:互联网 发布:c语言fprintf %s 编辑:程序博客网 时间:2024/04/29 16:43
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 #end010 011 #--------------------------- everything is a class ---012 puts "--------------------------- everything is a class ---"013 print "aaa/nbbb/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 puts021 022 #--------------------------- class and inspect ---023 puts "--------------------------- class and inspect ---"024 class Song025     def initialize(name, artist, duration)026         @name = name027         @artist = artist028         @duration = duration029     end030 end031 song = Song.new("Bob", "Tom", 20)032 puts song.inspect033 puts song.to_s034 035 #--------------------------- override to_s ---036 puts "--------------------------- override to_s ---"037 class Song038     def to_s039         "Song: #@name #@artist (#@duration)"040     end041 end042 puts song.to_s043 044 #--------------------------- read attribuite ---045 puts "--------------------------- read attribuite ---"046 class Song047     attr_reader :name, :artist, :duration048 end049 puts "song.name     = " + song.name050 puts "song.artist   = " + song.artist051 puts "song.duration = " + song.duration.to_s052 053 #--------------------------- write attribuite ---054 puts "--------------------------- write attribuite ---"055 class Song056     attr_writer :duration057     def name=(new_name)058         @name = new_name059     end060 end061 song = Song.new("Bicylops", "Fleck", 260)062 song.duration = 257063 song.name = "IamNewName"064 puts "song.duration = " + song.duration.to_s065 puts "song.name     = " + song.name066 067 #--------------------------- virtual attribute ---068 puts "--------------------------- virtual attribute ---"069 class Song070     def duration_in_minutes071         @duration/60.0 # force floating point072     end073     def duration_in_minutes=(new_duration)074         @duration = (new_duration*60).to_i075     end076 end077 song = Song.new("Bicylops", "Fleck", 260)078 puts "song.duration_in_minutes = " + song.duration_in_minutes.to_s079 song.duration_in_minutes=5080 puts "song.duration = " + song.duration.to_s081 082 #--------------------------- Singleton ---083 puts "--------------------------- Singleton ---"084 class MyLogger085     private_class_method :new086     @@logger = nil087     def MyLogger.create088         @@logger = new unless @@logger089         @@logger090     end091 end092 093 #--------------------------- access control ---094 puts "--------------------------- access control ---"095 class Accounts096     def initialize(checking, savings)097         @checking = checking098         @savings = savings099     end100 101     private102     def debit(account, amount)103         account.balance -= amount104     end105     def credit(account, amount)106         account.balance += amount107     end108 109     public110     #...111     def transfer_to_savings(amount)112         debit(@checking, amount)113         credit(@savings, amount)114     end115     #...116 end117 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 SongList132     def initialize133         @songs = Array.new134     end135 136     def append(song)137         @songs.push(song)138         self139     end140 141     def delete_first142         @songs.shift143     end144 145     def delete_last146         @songs.pop147     end148 149     def [](index)150         @songs[index]151     end152 153     def with_title(title)154         @songs.find {|song| title == song.name }155     end156 157 end158 159 require 'test/unit'160 class TestSongList < Test::Unit::TestCase161     def test_delete162         puts "--------------------------- unit testing ---"163         list = SongList.new164         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     end178 end179 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_s185 puts "inject product = " + [1,3,5,7].inject(1) {|product, element| product*element}.to_s186 187 #--------------------------- closure ---188 puts "--------------------------- closure ---"189 songlist = SongList.new190 class Button191     def initialize(label)192         @label = label193     end194 end195 class JukeboxButton < Button196     def initialize(label, &action)197         super(label)198         @action = action199     end200     def button_pressed201         @action.call(self)202     end203 end204 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 end212 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 = 3221 9.times do222     puts "#{num.class}: #{num}"223     num *= num224 end225 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 spaces235     print v1 + v2, " "236 end237 puts238 239 somelines.each do |line|240     v1, v2 = line.split241     print Integer(v1) + Integer(v2), " "242 end243 puts244 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 ' + a254                 end255                 the('time')256               } for all good coders..."257 258 print <<END_OF_STRING259     The body of the string260     is the input lines up to261     one ending with the same262     text that followed the '<<'263 END_OF_STRING264 265 print <<-STRING1, <<-STRING2266         Concat267         STRING1268             enate269             STRING2270 271 #--------------------------- string operation ---272 puts "--------------------------- string operation ---"273 File.open("songdata.txt", "r") do |song_file|274     songs = SongList.new275     song_file.each do |line|276         file, length, name, title = line.chomp.split(//s*/|/s*/)277         if !(file && length && name && title)278             next279         end280 281         name.squeeze!(" ")282         mins, secs = length.scan(//d+/)283         songs.append(Song.new(title, name, mins.to_i*60+secs.to_i))284     end285     puts songs[1]286 end287 288 #--------------------------- range ---289 puts "--------------------------- range ---"290 class VU291     include Comparable292     attr :volume293     def initialize(volume) # 0..9294         @volume = volume295     end296 297     def to_s298         inspect299     end300 301     def inspect302         '#' * @volume303     end304 305     # Support for ranges306     def <=>(other)307         self.volume <=> other.volume308     end309 310     def succ311         raise(IndexError, "Volume too big") if @volume >= 9312         VU.new(@volume.succ)313     end314 end315 316 medium_volume = VU.new(4)..VU.new(7)317 puts medium_volume.to_a318 medium_volume.include?(VU.new(3))319 320 #--------------------------- regex ---321 puts "--------------------------- regex ---"322 def show_regexp(a, re)323     if a =~ re324         "#{$`}<<#{$&}>>#{$'}"325     else326         "no match"327     end328 end329 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/nthe time", /^the/)334 puts show_regexp("this is/nthe time", /is$/)335 puts show_regexp("this is/nthe time", //Athis/)336 puts show_regexp("this is/nthe time", //Athe/)337 puts show_regexp("this is/nthe time", //bis/)338 puts show_regexp("this is/nthe 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 end349 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.dup369     str.gsub!(/&(.*?);/n) {370         match = $1.dup371         case match372             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).chr377             when //A#x([09af]+)/z/ni then $1.hex.chr378         end379     }380     str381 end382 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 TaxCalculator388     def initialize(name, &block)389         @name, @block = name, block390     end391     def get_tax(amount)392         "#@name on #{amount} = #{ @block.call(amount) }"393     end394 end395 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_one400     "one"401 end402 puts meth_one403 def meth_two(arg)404     case405     when arg > 0406         "positive"407     when arg < 0408         "negative"409     else410         "zero"411     end412 end413 puts meth_two(23)414 puts meth_two(0)415 416 def meth_three417     100.times do |num|418         square = num*num419         return num, square if square > 1000420     end421 end422 puts meth_three423 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 else434     puts((1..10).collect {|n| n+number }.join(", "))435 end436 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 else445     calc = lambda {|n| n+number }446 end447 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")         # => 4459 puts "123456789".count("2-8", "^4-6")  # => 4460 print "123/n".chomp461 puts " 123".chop462 puts " abc"*8463 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" % 13470 puts "123456789".delete("2378")           # =>"14569"471 puts "123456789".delete("2-8", "^4-6")    # =>"14569"472 puts "aBC".capitalize473 puts "aBC".upcase474 puts "aBC".downcase475 puts "aBC".swapcase476 puts "iloveyuchi".sub(/[aeiou]/, ".")477 puts "iloveyuchi".gsub(/[aeiou]/, ".")478 puts "123abc".hex479 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, ba503 puts504 =begin505 these506     are507         comments508 =end509 510 puts <<OOO511 here we are512 inline513 strings514 OOO515 516 #--------------------------- exception ---517 puts "--------------------------- exception ---"518 count = 0519 begin520     count += 1521     f = File.open("testfile")522     # .. process523 rescue524     # .. handle error525     puts "Got error!"526     retry if f.nil? && (count < 3)527 else528     puts "Congratulations, no errors!"529 ensure530     puts "Ensure file is closed!"531     f.close unless f.nil?532 end533 534 class RetryException < RuntimeError535     attr_reader :ok_to_retry536     attr_writer :ok_to_retry537     def initialize(ok_to_retry)538         @ok_to_retry = ok_to_retry539     end540 end541 542 $flag = false543 def read_data(socket)544     #data = socket.read(512)545     data = nil546     if data.nil?547         raise RetryException.new($flag), "transient read error"548     end549     # .. normal processing550 end551 552 begin553     $flag = !$flag554     #stuff = read_data(socket)555 #    stuff = read_data("")556     # .. process stuff557 rescue RetryException => detail558     if detail.ok_to_retry559         puts "Oh yeah, we got exception, let's try again"560         retry561     else562         puts "Oh shit, I give up"563         raise564     end565 end566 567 #--------------------------- array operations ---568 puts "--------------------------- array operations ---"569 puts ([1,3,5]&[1,2,3]).inspect570 puts ([1,3,5]|[1,2,3]).inspect571 puts ([1,3,5]*3).inspect572 puts ["foo", "bar"] * "-"     # => "foo-bar"573 puts ([1,3,5] - [1,2,3]).inspect574 puts ([1,3,5] + [1,2,3]).inspect575 puts ([1,3,5] << [4, 6]).inspect576 577 arr = [0, 1, 2, 3, 4, 5]578 arr[0..2] = ["a", "b"]     # arr => ["a", "b", 3, 4, 5]579 puts arr.inspect580 puts arr[1, 0] = ["c"]          # arr => ["a", "c", "b", 3, 4, 5]581 puts arr.inspect582 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.clear589 puts a.inspect590 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.inspect599 a.uniq! 600 puts a.inspect601 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"
原创粉丝点击