Ruby学习过程中积累下来的测试代码

来源:互联网 发布:隐秘录像 知乎 编辑:程序博客网 时间:2024/05/22 23:59

基础部分:

puts -1943.absdef say_goodnight(name)  yield  puts "Good night, " + nameendsay_goodnight("Shen Bin") { puts "Hi " }$greeting = "Hello"@name = "Shen Bin 1"puts "#$greeting, #@name"a = [1, 'cat', 3.14]puts a[-1]a = [1, 3, 5, 7, 9]puts a[1, 3]puts a[1..3]puts a[1...3]person1 = "Shen Yan"person2 = person1person1[0] = "C"puts person2person3 = person1.dupperson1[0] = "S"puts person3class File  def File.open_and_process(*args)    result = f = File.open(*args)    if block_given?      result = yield f      f.close()    end    return result  endendFile.open_and_process("D:/rails.txt", "r") do |file|  while line = file.gets    puts line  endend['cat', 'dog', 'horse'].each { |name| print name, " "}["H", 'A', "B"].collect { |x| x.succ }a = ['3 4', '5 6', '7 8']a.each do |line|  v1, v2 = line.split#  print v1 + v2, " "  print Integer(v1) + Integer(v2), " "enda = %w{ ant bee cat dog elk }puts a[1]b = Hash.new(0)  # Hash.new 0b['key1'] += 1;puts b['key1']a = %w{ ant bee cat dog elk }a.each { |a| puts a if a =~ /\w{2}t/ }puts '-------------------------'puts a.grep(/\w{2}t/)

类,对象:

class Song  attr_reader :artist, :duration  attr_writer :artist  attr_accessor :name    def initialize(name, artist, duration)    @name = name    @artist = artist    @duration = duration  end    def to_s    "Song: #@name -- #@artist (#@duration)"  end    def duration=(new_duration)    @duration = new_duration  endendsong = Song.new('a', 'b', 100)#puts song.inspectputs song.to_ssong.name = 'c'song.artist = 'd'song.duration = 600puts song.to_sputs song.name + " | " + song.artist + " | " + String(song.duration)
类变量:

class Song  @@plays = 0  def initialize(name, artist, duration)    @name = name    @artist = artist    @duration = duration    @plays = 0  end    def play    @plays += 1    @@plays += 1    puts "This song: #@plays plays. Total #@@plays plays."  endends1 = Song.new('Song1', "Artist1", 234)s2 = Song.new('Song2', "Artist2", 345)s1.plays1.plays2.plays1.play
Block,闭包

def fibonacci_up_to(max)  x, y = 1, 1  while x < max    if(block_given?)       yield x    end    x, y = y, x+y  endendfibonacci_up_to(1000) { |f| print f, " "}def n_times(thing)  return lambda { |n| thing * n }endp1 = n_times(23)puts p1.call(3)puts p1.call(4)p2 = n_times('Hello ')puts p2.call(2)
each和collect的区别 --- 返回值不同

a = [1, 2, 3]b = a.each { |i| i*2 }puts bc = a.collect { |i| i*2 }puts c
标准类型:数字/字符串/区间等

a = 123_456_789puts aputs a.classb = "Now is #{  def the(a)    'The ' + a  end  the('time')} for all good coders..."puts bc = %q/generate single-quoted string/d = %Q!generate double-quoted string!e = %Q{Secounds/Day: #{24*60*60}}puts c,d,ef = <<HERE_DOCUMENT_STRING  Hello, Shen Bin.  We are using Ruby.HERE_DOCUMENT_STRINGputs fg = (0 .. 10).to_ah = ('bar' .. 'bat').to_aputs g, hi = (0 .. 10) === 5j = (0 .. 10) === 15k = ('a' .. 'j') === 'c'l = ('a' .. 'j') === 'o'puts i, j, k, l

如果方法定义的最后一个参数的前缀为&,那么所关联的block会被转换为一个Proc对象,然后赋值给这个参数

class TaxCalculator  def initialize(name, &block)    @name, @block = name, block  end  def get_tax(amount)    "#@name on #{amount} = #{ @block.call(amount) }"  endendtc = TaxCalculator.new("Sales Tax") { |amt| amt * 0.075 }puts tc.get_tax(100)puts tc.get_tax(250)

使用lambda表达式抽取block

print "(t)imes or (p)lus"t = getsprint "number: "m = gets.to_iif t =~ /^t/  puts ((1..10).collect { |n| n * m }.join(", "))else  puts ((1..10).collect { |n| n + m }.join(", "))end#使用lambda表达式把block抽取出来print "(t)imes or (p)lus"t = getsprint "number: "m = gets.to_iif t =~ /^t/  calc = lambda { |n| n * m }else  calc = lambda { |n| n + m }endputs ((1..10).collect(&calc).join(", "))

If / case when等表达式也可以有返回值:

a = getsb = if a.to_i > 0  1elsif a.to_i == 0  0else  -1endputs b
覆盖已有方法
class Fixnum  alias plus +  def +(other)    plus(other).succ  endendputs 1+1a = 3puts a += 4puts a+a+a
反引号`以及%x --- 将被操作系统当做命令来执行

puts `dir`puts %x{ echo 'Hello World'! }

在Ruby1.8以后,赋值语句的值总是参数的值而方法的返回值将被丢掉

class Test  def val=(val)    @val = val    return 99  endendt = Test.newa = t.val = 2puts a

self的作用(区别)

class BrokenApmlifier  attr_accessor :left, :right  def volume=(vol)#    @left = @right = vol    left = self.right = vol  endendba = BrokenApmlifier.newba.left = ba.right = 3ba.volume = 5puts ba.leftputs ba.right
并行赋值:

x = 0a, b, c = x, x+=1, x+=1print a, ' ', b, ' ', c#交换两个变量的值a, b = b, aa = [1, 2, 3, 4]b, c = a            # b == 1, c == 2b, *c = a           # b == 1, c == [2, 3, 4]b, c = 99, a        # b == 99, c == [1, 2, 3, 4]b, *c = 99, a       # b == 99, c == [[1, 2, 3, 4]]b, c = 99, *a       # b == 99, c == 1b, *c = 99, *a      # b == 99, c == [1, 2, 3, 4

嵌套赋值

b, (c, d), e = 1, 2, 3, 4               # b == 1, c == 2, d == nil, e == 3b, (c, d), e = [1, 2, 3, 4]             # b == 1, c == 2, d == nil, e == 3b, (c, d), e = 1, [2, 3], 4             # b == 1, c == 2, d == 3, e == 4b, (c, d), e = 1, [2, 3, 4], 5          # b == 1, c == 2, d == 3, e == 5b, (c, *d), e = 1, [2, 3, 4], 5         # b == 1, c == 2, d == [3, 4], e == 5

#注意,Ruby不支持C或Java中自增(++)和自减(--)运算,需要使用(+=)或(-=)代替。

变量作用域:

x = y = nil # 此处不定义的话程序会抛错[1, 2, 3].each do |a|  x = a  y = x + 1endputs x, y

网络编程:

require 'net/http'h = Net::HTTP.new('www.yahoo.com', 80)response = h.get('/')if response.message == 'OK'  puts response.body.scan(/<img src=".*?"/m).uniqend
动态创建:

5.times do |i|  File.open('temp.rb', "w") do |f|    f.puts "module Temp"    f.puts " def Temp.var"    f.puts "    #{i}"    f.puts " end"    f.puts "end"  end  load "temp.rb"  puts Temp.varend


原创粉丝点击