Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Ruby Language for Beginners, Part 2: Ruby Methods

DZone's Guide to

Ruby Language for Beginners, Part 2: Ruby Methods

We continue our series with a look at Ruby methods and variables and how developers work with these facets of the language.

· Web Dev Zone ·
Free Resource

Access over 20 APIs and mobile SDKs, up to 250k transactions free with no credit card required

Hello!

This is a post from the Ruby Language for Beginners in 8 Parts!

  • Part 1 - Ruby Characteristics and first Ruby code

  • Part 2 - Ruby Methods and Variables

  • Part 3 - Ruby Strings

  • Part 4 - Ruby Classes, Objects, and Instances

  • Part 5 - Ruby Conditionals

  • Part 6 - Ruby Arrays

  • Part 7 - Ruby Hashes

  • Part 8 - Ruby Loops

In the today's post, we're going to look at Methods and Variables in Ruby

Ruby Methods

Let's create the following mathematical calculation:

puts 1 + 2

puts 4 + 2

puts is a Ruby method. Actually, it's a built-in Ruby method and we can create our own Ruby methods.

We could create a calculator to add numbers by creating a method called sum, receiving 2 parameters:

def sum(a, b)
  return a + b
end

puts sum(1, 2)

puts sum(4, 2)

Notice the pattern to create a Ruby method:

def your_method_name
# your awesome logic here!
end

Ruby is really smart and you don't need to use the return keyword:

def sum(a, b)
  a + b
end

Ruby evaluates the last expression and returns that!

Just remember, we don't need to use parentheses when calling a method:

puts sum 1, 2

puts sum 4, 2

Let's jump into Ruby Variables!

Ruby Variables

We need to keep values somewhere, right? 

Let's create a method to sum up 10 to a given number and then return the result:

def sum_by_ten number
  ten = 10
  sum = number + ten
  return sum
end

puts sum_by_ten 5

As you can see, we created the variable ten to hold the value 10.

Can we change the variable in the middle of the program? Yes, we can!

def sum_by_five number
  five = 5
  sum = number + five
  # changing in the middle of the game!
  five = 10
  puts five
  return sum
end

puts sum_by_five 10

The output will be:

10
15

Changing the Type of the Variable

Ruby has another important characteristic: you can change the type of the variable, even after you've initiated it.

In the previous example, we had the following Ruby code:

ten = 10
puts ten
ten = "My value 10"
puts ten

This is totally fine in Ruby!

That's it! In the next post: Part 3 - Ruby Strings we're going to look at Ruby Strings!

I hope that this will be useful to you!

Thanks!

#1 for location developers in quality, price and choice, switch to HERE.

Topics:
ruby ,ruby objects ,web app ,ruby classes ,tutorial ,beginner

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}