shijiang1130 发表于 2009-09-26 23:34

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

cinanine 发表于 2010-12-15 17:31

很好用的功能:em50:

laohuanggua 发表于 2010-12-23 01:06

#!/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

2gua 发表于 2010-12-23 10:26

puts "#{sum1}"

zhlong8 发表于 2010-12-23 10:33

这个语法高亮是怎么搞的?

2gua 发表于 2010-12-23 10:42

回复 5# zhlong8


    两种方式:一个个关键字设置,网络复制。
页: [1]
查看完整版本: ruby 迭代器