RUBY迭代器小例子
RUBY迭代器是一个调用block的方法求平均值
Ruby代码
grades = [88,99,73,56,87,64]
sum = 0
0.upto(grades.length - 1) do |loop_index|
sum += grades[loop_index]
end
average = sum / grades.length
puts average求4到12之间的偶数的和:
Ruby代码
puts "Whats the answer?"
sum = 0
4.step(12, 2) do |even_value|
sum += even_value
end
puts "The answer is " + sum.to_s;很漂亮的求平均值的迭代器:
Ruby代码
grades = [88,99,73,56,87,64]
sum = 0
grades.each do |grade|
sum += grade
end
average = sum / grades.length
puts average例如,从1循环到10,可以这么写:
for i in 1..10 do
puts i
end
但是ruby更倾向于使用迭代器方法:
(1..10).each do |i| puts i end
上述当然还有upto这个方法:
1.upto(10) do |i| puts i end
其他的迭代器方法还包括:
打印文件里每一行:
File.new("a.txt").each_line do |s|
puts s
end
列举目录里每一个文件:
Dir.foreach("/tmp") do |d| puts d end
访问数组的每个元素:
arr = [3,2,1,4,0]
arr.each do |e| puts e end
访问数组的下标:
arr.each_index do |i| puts i end
访问串的每一个字符:
s="hello"
s.each_byte do |w| puts w.chr end
访问哈希的每一对键值:
x={"a"=>1,"b"=>2,"c"=>3}
x.each do |k,v| puts "#{k} #{v}" end
遍历哈希的每一个键:
x.each_key do |k| puts k end
遍历哈希的每一个值:
x.each_value do |v| puts v end
等等。
当然自己写一个迭代器方法也一点不难,例如,模拟数组的each方法,写一个myeach。x = [3,2,4,0,1]
class Array
def myeach
for i in self do
yield i
end
end
end
x.myeach {|s| puts s }
补充:综合编程 , 其他综合 ,