delete
delete

Reputation:

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
  while 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?

Upvotes: 2

Views: 139

Answers (4)

JCLL
JCLL

Reputation: 5545

def display_multiples(of,nb)
  p (of..of*nb).step(of).to_a
end

display_multiples(3,5) #display [3, 6, 9, 12, 15]

Upvotes: 0

steenslag
steenslag

Reputation: 80065

def display_multiples(number, limit)
  0.step(limit, number){|n| puts n}
end

Upvotes: 2

Christopher Creutzig
Christopher Creutzig

Reputation: 8774

def display_multiples(multiplesOf, count)
  (count/multiplesOf).times {|x| puts (x+1) * multiplesOf }
end

As for documentation, see ruby-doc.org and gotapi.com.

Upvotes: 1

yan
yan

Reputation: 20982

I'd do:

def display_multiples(multiplesOf, count)
  count.times {|x| puts x * multiplesOf }
end

Upvotes: 4

Related Questions