Is there a more ruby-esque way to do this?
I'm learning Ruby since yesterday evening.
Here's a method I made that's supposed to print out multiples of any numbers up to any quantity.
def DisplayMultiples(multiplesOf, count)
i = multiplesOf
wh开发者_如何学JAVAile i <= count
if i % multiplesOf == 0
puts i
end
i += 1
end
end
Any suggestions on how to improve the code to something more fitting to the Ruby style? I'm coming from a C# background so I'd like to switch things up a bit.
Edit:
Where can I find documentation for methods/classes? For example, the first answer I received use the .times method (is it a method?). I can't find the documentation for that because I don't know what type it is, since Ruby doesn't have types.
Any suggestions?
I'd do:
def display_multiples(multiplesOf, count)
count.times {|x| puts x * multiplesOf }
end
def display_multiples(number, limit)
0.step(limit, number){|n| puts n}
end
def display_multiples(multiplesOf, count)
(count/multiplesOf).times {|x| puts (x+1) * multiplesOf }
end
As for documentation, see ruby-doc.org and gotapi.com.
def display_multiples(of,nb)
p (of..of*nb).step(of).to_a
end
display_multiples(3,5) #display [3, 6, 9, 12, 15]
精彩评论