On Fri, May 6, 2011 at 8:18 AM, Super Goat <ruby-forum / sgoat.33mail.com> wrote:
> I am still trying to wrap my head around Methods.   > know how to put down the code.     
> a bit confused but I have a feeling that using Methods is a very Rubyist
> thing and the way Ruby was intended to be written.

A method is just a block of code with a name that can be invoked from
other points in the code.
It can receive parameters, which are like local variables within the method.
For example:

def say what, who
  puts "Hi, #{who}, did you know that #{what}?"
end

say "the sky is blue", "Mike"
say "my name is Jesus", "Tom"

and so on. When you need to reuse a piece of logic, it's usually a
good idea to put it in a method.


> I am going to try to use a Method and make this work and see if I can
> figure out how to reject any input that isn't a number (probably isn't
> hard just don't know how yet).

You already know how to use to_i. If you use it on a string that isn't
a number it will return 0.
If you need to check if the full string is a valid number, you can use
Kernel#Integer, which will raise an exception:

ruby-1.8.7-p334 :001 > "abc".to_i
 => 0
ruby-1.8.7-p334 :002 > Integer("abc")
ArgumentError: invalid value for Integer: "abc"
	from (irb):2:in `Integer'
	from (irb):2

You can do:

def get_valid_input
  loop do
    puts "Input a number between 0 and 100"
    choice = Integer(gets.chomp) rescue nil # this will evaluate to
nil if the string isn't a number
    return choice if choice && (0..100).include?(choice)
  end
end

As others have said, I recommend you get familiar with IRB
(Interactive Ruby), it's a wonderful tool to explore Ruby, test little
pieces of code, explore which methods an object has, etc. You can also
take a look here: http://ruby-doc.org/core/ to explore the core
classes (start with String, Array and Hash).

Jesus.