Blocks and Sorting Ruby

feelo31

Felix Imbanga

Posted on March 1, 2024

Blocks and Sorting Ruby

This is a good example of methods and splat arguments from codeacademy's training

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

what_up("What up", "Ian", "Zoe", "Zenas", "Eleanor")
Enter fullscreen mode Exit fullscreen mode

Methods are reusable sections of code that perform a specific task in a program

seperation of concerns- make program less redundant and code more readable.

Methods defines a new
-header include the def key word
-Body included the procedure the methods carries out
-end includes the end key word
argument - code that you put between a methods parenthesis when you call it, parameter is the name you put between methods parenthesis when you define it.

Splat argument - argument preceding an asterisk. tells program you can use 1 or more arguments

puts always returns nil when included in a method. you must use something like return because puts will be evaluated in the expression

ruby evaluates for expression truthiness/falsiness. An expression in ruby will inherently return a boolean value when used in a context that expects a boolean. Without needing explicit statements of return false or return true.

abstraction - making something simpler.

sort is non destructive while sort! is destructive. the first stores original string while the latter erases and completely creates a new string. they each have their benefits based on what you plan on doing with your code.

<=> means if 1>2 then 1 is returned, if 1<2, -1 is returned, and if the values are equal 0 is returned. Also be careful not to set this equal to a variable because ruby will print out the numeric value to the console, rather than ordered strings.

đź’– đź’Ş đź™… đźš©
feelo31
Felix Imbanga

Posted on March 1, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related