DEV Community

salcasta
salcasta

Posted on

Ruby Basics - Methods and Sorting

Methods

A method is very similar to a function in JavaScript. You start off by using def and then the name of the method.
Parentheses follow the method name is it requires a parameter. Then you insert your reusable code and end it with the word 'end'.

It should look like this...

def cubertino(n)
  puts n ** 3
end
Enter fullscreen mode Exit fullscreen mode

To call it (use it) just use the name of the method with an argument in parentheses

cubertino(8)

# 512
Enter fullscreen mode Exit fullscreen mode

To make multiple arguments just put an asterisk in front of the parameter

def what_up(greeting, *friends)
  friends.each { |friend| puts "#{greeting}, #{friend}!" }
end

what_up("What up", "Ian", "Zoe", "Zenas", "Eleanor")

Output: 
What up, Ian!
What up, Zoe!
What up, Zenas!
What up, Eleanor!
Enter fullscreen mode Exit fullscreen mode

Using return inside your method will give you back a value, this value can be used for another method.

Sorting

Using sort will reorganize your string data from A-Z or your numerical data from 1-n.

To get the opposite order, use arrow notation to set which order you would like.

books = ["Charlie and the Chocolate Factory", "War and Peace", "Utopia", "A Brief History of Time", "A Wrinkle in Time"]

# To sort our books in ascending order, in-place
books.sort! { |firstBook, secondBook| firstBook <=> secondBook }

# Sort your books in descending order, in-place below

books.sort! { |firstBook, secondBook| secondBook <=> firstBook }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)