开发者

Is there a more ruby-esque way to do this?

开发者 https://www.devze.com 2023-02-11 01:25 出处:网络
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.

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]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号