Trying to experiment with methods


#1

Hello, I'm fooling around a bit with methods. I have no issues with integers, but when I get to strings, I run into problems. I have a question I was hoping someone could help me with. This code runs fine of itself, but I was wondering how I would write it as a method?

puts "What is your age?"
age = gets.chomp

puts "#{age} ain't nothing but a number!"

I've tried a bunch of possibilities to no avail. Any help would be much appreciated, thanks


#2

@nycwebs212,

def my_function(param)
  puts "#{param}"
end

my_function("hallo")


def get_and_display_age()
  puts "What is your age?"
  age = gets.chomp

  puts "#{age} ain't nothing but a number!"
end

get_and_display_age()

#3

This is known as value interpolation where value can be any expression. This is based on the definition of an expression which is any construct that yields a value.

a = 3
b = 4
puts "#{a**2 + b**2}"    # 25

a = 1
b = -1
c = -2
x1 = ((-b) - (b**2 - 4 * a * c)**0.5) / 2 * a
x2 = ((-b) + (b**2 - 4 * a * c)**0.5) / 2 * a
puts "(#{x1}, #{x2})"      # (-1.0, 2.0)

x = [
    ((-b) - (b**2 - 4 * a * c)**0.5) / 2 * a,
    ((-b) + (b**2 - 4 * a * c)**0.5) / 2 * a
    ]
puts "#{x[0]}, #{x[1]}"    # -1.0, 2.0

def find_roots(a,b,c)
    s = b**2 - 4 * a * c
    if s < 0
        return ["no Real root","no Real root"]
    else
        d = s**0.5
        return [
            ((-b) - d) / (2 * a),
            ((-b) + d) / (2 * a)
        ]
    end
end
x = find_roots(-1,-1,-2)
puts "#{x[0]}, #{x[1]}"    # no Real root, no Real root
x = find_roots(-1,1,2)
puts "#{x[0]}, #{x[1]}"    # 2.0, -1.0

henceforth...

def zeroes(a,b,c)
    x = find_roots(a,b,c)
    puts "(#{x[0]}, 0), (#{x[1]}, 0)"
    return x
end

x = zeroes(1,-1,-2)      # [-1.0, 2.0] prints as (-1.0, 0), (2.0, 0)