DEV Community

Isabelle Bessa
Isabelle Bessa

Posted on

Ruby and it's many, many (many) methods.

When told that Ruby was an Object Oriented Programming language, my first thought was: and? What is it that ruby can do that JavaScript (and React.js <3) can't?

The answer to that is nothing. There's nothing ruby can do that can't be recreated with JS (well, except deal with high CPU intensive application development, but that's for another blog post). The main thing is: It can do it in a faster and simpler way than JS would ever think of doing it.

And how is that possible? you may ask. Ruby has a lot of methods, which are a set of expressions that return a value. With it, it's easier to access and modify your code along the needs of your project. We won't be covering all of them here, because there would not be enough space. Instead, let's just go over the basics.

Eleanor gets it

.first

You know how when calling elements out from an array, you have to do the whole index thing? Array[0], or Array.obj[1], and it gets progressively worse? Ruby solved that for you. All you need to do is literally call the first element.

array = [1,2,3,4,5]
array.first
=> 1
Enter fullscreen mode Exit fullscreen mode

What if I want the second element?

array = [1,2,3,4,5]
array.second
=> 2
Enter fullscreen mode Exit fullscreen mode

But that can't work for all of the elements. Can it?

array = [1,2,3,4,5]
array.third
=> 3
Enter fullscreen mode Exit fullscreen mode

*It can!!!!!!!!!!! *

We must stan

.include?

That one sounds simple enough. We want to check if our element is included in the array we're searching through.

array = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
array.include?(3)
=> true
Enter fullscreen mode Exit fullscreen mode

.join

This one is my pride and joy(n). You can call an array and transform it into a string, with a separator parameter.

array.join
=> "1234"
array.join("*")
=> "1*2*3*4"
Enter fullscreen mode Exit fullscreen mode

.uniq

As the name says, this iterates over an array and returns only one of each element that's in it. All the duplicate elements are removed from the array.

array = [1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 6, 7, 8]
array.uniq
=> [1, 2, 3, 4, 5, 6, 7, 8]
Enter fullscreen mode Exit fullscreen mode

.drop_while

It's a simpler way to select elements in your array. It drops elements up to, but not including, the first element for which the block returns nil or false and returns an array containing the remaining elements.

a = [1, 2, 3, 4, 5, 0]

a.drop_while { |i| i < 3 }   
=> [3, 4, 5, 0]

Enter fullscreen mode Exit fullscreen mode

Now that you've seen how easy and intuitive ruby methods are, are you interested in learning more of them? Try it out and happy coding!

Sources

https://www.freecodecamp.org/news/common-array-methods-in-ruby/

https://apidock.com/ruby

Top comments (0)