带参数的范围

时间:2016-02-04 13:33:29

标签: ruby

def crazynum(number)

  sum = [0..number.length]
  sum.select do |i|
     if ((i%3 == 0) || (i %5 == 0)) && !((i%3 == 0) && (i %5 == 0))
       array<<i
     end
  end

  puts array.inspect

end

puts crazynum(10)

如何使用(1..number.length)等范围?使用selecteach方法?

有人可以向我解释为什么我会收到以下错误吗?

$ ruby crazy_select.rb
crazy_select.rb:3:in `crazynum': undefined method `length' for 10:Fixnum
(NoMethodError)
from crazy_select.rb:11:in `<main>'

1 个答案:

答案 0 :(得分:0)

假设你只是在 fizzes(3的倍数)之后,嗡嗡声(5的倍数)而不是 fizzbuzzes(3和5的倍数)< / em>,那么我认为这就是你要做的事情:

def crazynum(n)
  array=[]
  (1..n).each do |i|
    if ( i%3 == 0 || i%5 == 0 ) && !( i%3 == 0 && i%5 == 0 )
      array << i
    end
  end
  p array
end

crazynum(10) #=> [3, 5, 6, 9, 10]
#to check an example of fizzbuzz doesn't appear
crazynum(16) #=> [3, 5, 6, 9, 10, 12]

或者,如果您想使用select,请尝试:

def crazynum(n)
  (1..n).select do |i|
    ( i%3 == 0 || i%5 == 0 ) && !( i%3 == 0 && i%5 == 0 )
  end
end

p crazynum(10) #=> [3, 5, 6, 9, 10]
#to check an example of fizzbuzz doesn't appear
p crazynum(16) #=> [3, 5, 6, 9, 10, 12]