Did you know that using the right Ruby method can save you a lot of work?
The more methods you are familiar with the faster you can produce working code & the better this code will be, both in performance & quality.
That’s why today I want to introduce 7 interesting methods to you that you may not have seen before.
Contents
Integer#digits Method (Ruby 2.4)
This is a new method introduced in Ruby 2.4 & it’s very useful if you want to work with the individual digits of an Integer.
Note: In case you are not up to speed on Ruby 2.4 changes, Fixnum & Bignum are now deprecated & both merged into Integer.
You may think that using array-like indexing may work:
2[0]
# 0
2[1]
# 1
But what you get are not the digits, but the binary bits that make up this number.
So pre-digits method the typical solution was to convert the number into a string, then break that string into an array of characters using the chars method, and finally convert every string back into an integer.
Example:
123.to_s.chars.map(&:to_i).reverse
[3, 2, 1]
But in a post-digits method world, you can simply do this:
123.digits
[3, 2, 1]
Much better, isn’t it?
Video:
The Tap Method
Sometimes you want to create an object, call some methods on it & return that same object.
You would have to do something like this:
user = User.new
user.name = "John"
user
The problem is that we have to deal with this temporary variable.
Here’s where the tap method comes to the rescue!
With tap the last example becomes this:
User.new.tap { |user| user.name = "John" }
Notice how the temporary variable is gone, which is a good thing 🙂
Array#values_at
If you want to get multiple non-sequential values from an array or a hash you could do this:
arr = [1,2,3,4,5]
a, b, c = arr[0], arr[1], arr[4]
Or you could use the values_at method:
arr = [1,2,3,4,5]
a, b, c = arr.values_at(0, 1, 4)
That was pretty helpful. I knew couple of methods and have used ’em in the past, but some of ’em really looks interesting. Cant wait to play with ’em. Thank you Jesus!