ruby 迭代器
ruby的迭代器是一个很好用的功能examples = [88,99,73,56,87,64]
total = 0
0.upto(examples.length - 1) do|loop_index|
total+= examples[loop_index]
end
average = total/ examples.length
puts average
4.step(12, 2) do | even_value |
sum += even_value
end
puts "The answer is " + sum.to_s
4.times do
puts "1234"
end 很好用的功能:em50: #!/usr/bin/ruby -w
array1=
total=array1.inject(0){|sum,arg|sum+arg.to_i}
p "#{total}"
0.upto(array1.length-1) do |f|
sum1+=array1
end
p "#{sum1}"
结果后一个迭代报错!
# ruby 7.rb
"22"====如何把这个引号给去掉??
7.rb:9: undefined method `+' for nil:NilClass (NoMethodError)
from 7.rb:8:in `upto'
from 7.rb:8 puts "#{sum1}" 这个语法高亮是怎么搞的? 回复 5# zhlong8
两种方式:一个个关键字设置,网络复制。
页:
[1]