Using the right Ruby methods 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. To improve your productivity, here are some helpful methods that you may not have seen before.
Prefix & Suffix Methods
start_with?
& end_with?
return boolean results based on whether the beginning or end of a string match the provided string.
delete_suffix
and delete_prefix
remove from the beginning or end of a string if the suffix or prefix match the provided string.
Percent String Literals
Besides %(...) which creates a String, the % may create other types of object. As with strings, an uppercase letter allows interpolation and escaped characters while a lowercase letter disables them. For the two array forms of percent string, if you wish to include a space in one of the array entries you must escape it with a “\” character.
These are the types of percent strings in ruby:
%i
- Array of Symbols
%q
- String
%r
- Regular Expression
%s
- Symbol
%w
- Array of Strings
%x
- Backtick (capture subshell result)
Convert Number to an Array of Digits
the digits
method returns an array of a number's digits in reverse.
123.digits => [3, 2, 1]
The Object Tap Method
The tap
method allows you to perform an action on an object then return the object.
Instead of:
user = User.new
user.name = "John"
user
You can write:
User.new.tap { |user| user.name = "John" }
The new object will be returned after performing the operation which avoids using a temporary variable.
Transforming Multiple Hash Values
When you need to transform all of the values in a hash, say doubling your inventory, you can use the transform_values
method.
Instead of:
inventory = {item_A: 200, item_B: 300}
inventory.each { |k,v| h[k] = v*2 }
You can use:
inventory = {item_A: 200, item_B: 300}
inventory.transform_values! { |v| v * 2 }
{:item_A=>400, :item_B=>600}
Top comments (0)