HOW TO?!

7.29.15


After overlooking all of the enumerable choices, I felt the most important was to cover the .each method. This method has to power to go through each element of an array or a hash. This gives the method to power to set a vairable name to each element that exists inside it. Here is a quick example of how you may call an each method to a specific array...

def mode(array)

array.each do |num|

As you can see the .each method is calling to look through every single element and give it a variable name of num. This is so you can easily call to the individuals in the array by a simple variable called num.

.each is also very univeral in that you can _ add-ons to the method teliing it to do other specific things. Some of these include each_char, which seperates each chracter into its own seperate string. There are also each methods specific to hashes such as each_key and each_value. The key method allows you to call on a specific key within the hash. And value doing the exact same but with the value slot instead of key. Here are a few examples...

This calls for each letter to be split by a space(' ') ruby

"hello".each_char {|c| print c, ' ' }

Produces

h e l l o

This examples is calling for the values, not keys

h = { "a" => 100, "b" => 200 } h.each_value {|value| puts value }

Produces

100

200

The each method is very universal and has many different ways to use it, many more than what I just showed you here. If you have any questions or find any mistakes. Please feel free to contact me immediately.