Topic: writing a method to give range from 1 to a number

I just started working with Ruby about a week ago, so I'm still trying to learn all of the basics.

How would I go about writing my own method that only takes one argument (a number) and then gives all the numbers from 1 to that number?  I know that 1..10 will give me a range from 1-10, but I don't understand how to get the range when there is a variable involved.

Thanks!

Re: writing a method to give range from 1 to a number

You can just use the variable in the same way, e.g.

bob = 10
range = 1..bob
puts range.to_a

and you'll see [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] as the output.

if you want to do something without assigning the range to a variable, remember to use parentheses:

puts (1..bob).to_a
Rob Anderton
TheWebFellas

Re: writing a method to give range from 1 to a number

Thanks, I understand that now.  However now I have to add to this same method to say if my variable is less than one it should print a phrase saying "this is less than one"

This is what I have so far:

def counter(num)

range = 1..num
puts (1..num).to_a

end

counter(15)


If what I put in for num is less than one, the program should tell me that.  I know I should put an if statement, but every time I put it in there and try to run it I just get errors.  Any suggestions?

Re: writing a method to give range from 1 to a number

def counter(num)
  return puts "num is smaller than 1" if num < 1
  range = 1..num
  puts (1..num).to_a
end

counter(0)
>> num is smaller than 1

Re: writing a method to give range from 1 to a number

I appreciate that this is just a learning exercise, but you are mixing presentation (puts) with functionality (returning an array of numbers). This makes the error handling hard to track, because when your code calls the method, you can't easily determine programatically if you have a good result or a bad one. So

def counter(num)
  num >= 1 ? (1..num).to_a : "#{num} must be >= 1"
end

puts counter(5)
puts counter(0)

would be better, and

def counter(num)
  raise ArgumentError, "Argument must be >= 1" unless num >= 1
  (1..num).to_a
end

puts counter(5)
puts counter(0)

may be better still. Note that Ruby returns the result of the last-executed statement as the return value from a method; in practice this means that you rarely need to code an explicit return statement unless you need to exit early, and the normal convention is to omit it.

Re: writing a method to give range from 1 to a number

I see your point and thanks for explaining it smile