早上在rubychina看到有人贴了一段99乘法表的一小段ruby代码。
1
i=1
2
while i<=9
3
j=1
4
while j<=i
5
s=j*i
6
print("#{j}*#{i}=#{s}\t")
7
j=j+1
8
end
9
print("\n")
10
i=i+1
11
end
i=12
while i<=93
j=14
while j<=i5
s=j*i6
print("#{j}*#{i}=#{s}\t")7
j=j+18
end9
print("\n")10
i=i+111
end这里是输出:
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81 这段代码觉得写的太罗嗦了,不像是ruby的风格。于是改成下面的code:
1
(1..9).each {|i|
2
(1..i).each{|j| print "#{j}*#{i}=#{i*j}\t";}
3
print("\n")
4
}
(1..9).each {|i| 2
(1..i).each{|j| print "#{j}*#{i}=#{i*j}\t";} 3
print("\n")4
}这样也行:
1
1.upto(9) {|i|
2
i.times {|j| print "#{j+1}*#{i}=#{i*(j+1)}\t"; }
3
print("\n")
4
}
1.upto(9) {|i| 2
i.times {|j| print "#{j+1}*#{i}=#{i*(j+1)}\t"; }3
print("\n")4
}是不是简单很多?
不过如果看了Programming Ruby中的例子,会有更深的印象:ruby好简单,好方便!!
这个例子是从一个歌曲list中根据序号或者名字来查找歌曲,下面是最初的做法,当然也是一般语言的通常做法:
1
class SongList
2
def [](key)
3
if key.kind_of?(Integer)
4
return @songs[key]
5
else
6
for i in 0
@songs.length
7
return @songs[i] if key == @songs[i].name
8
end
9
end
10
return nil
11
end
12
end
13
14
class SongList2
def [](key)3
if key.kind_of?(Integer)4
return @songs[key]5
else6
for i in 0
@songs.length7
return @songs[i] if key == @songs[i].name8
end9
end10
return nil11
end12
end13

14

然后是第二种做法:循环被一个find方法所取代,更加方便简洁了
1
class SongList
2
def [](key)
3
if key.kind_of?(Integer)
4
result = @songs[key]
5
else
6
result = @songs.find { |aSong| key == aSong.name }
7
end
8
return result
9
end
10
end
11
12
还有更简单的形式:
class SongList2
def [](key)3
if key.kind_of?(Integer)4
result = @songs[key]5
else6
result = @songs.find { |aSong| key == aSong.name }7
end8
return result9
end10
end11

12

1
class SongList
2
def [](key)
3
return @songs[key] if key.kind_of?(Integer)
4
return @songs.find { |aSong| aSong.name == key }
5
end
6
end
7
8
class SongList2
def [](key)3
return @songs[key] if key.kind_of?(Integer)4
return @songs.find { |aSong| aSong.name == key }5
end6
end7

8

从上面的例子来看,ruby是不是很方便,iterator的功能是不是很贴心?
对ruby的了解越多,越感到简单就是美!

浙公网安备 33010602011771号