One-liner Code Every Ruby Developer Should Know

Abhishek Tiwari
tech-tree
Published in
4 min readMay 9, 2021

Almost everything in Ruby is an object.
This makes it possible to save lines of code as each object offers multiple useful methods to use directly.
I will be listing down few code requirements which we often get and we will see their one-line and single statement implementations in Ruby.
Sounds interesting? Let’s go!!!

Array Selection

# We have an array 
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# list all the even elements of the array
arr.select {|a| a.even?}
# list all the odd elements of the array
arr.reject {|a| a.even?}
# list all elements other than first few elements smaller than 5
arr.drop_while {|a| a < 5}

In the above statements, we are iteratively visiting each element and filtering out some elements with conditions, and returning the filtered elements in just one line.

Though it returns the filtered result, it doesn’t change the original array. If we wish to do so, all we need to do is add ! at the end of methods, this still keeps it one line only

# update arr to contain only even elements
arr.select! {|a| a.even?}

We have few other methods which return and update the original array also, without ! at the end of method names

# update arr to contain only even elements
arr.keep_if {|a| a.even?}
# remove all even elements from arr
arr.delete_if {|a| a.even?}

We can extend the usage of these methods and apply them on ruby hash objects also:-

# We have a hash h
h = {2 => 20, 3 => 60, 4 => 80}
# keep only those key value pairs where key is even
h.keep_if {|k, v| k.even?}
# remove those key value pairs where key is even
h.delete_if {|k, v| k.even?}

Hash initialization with a default value

We often use the hash to check some flags or values for some keys, in some cases the key is not even present in the hash and we need to add another statement to check if the key is present or not, then we check for its value.
We have a better way of tackling this with just one line change so that we can avoid having to check for non-existing keys

# We have a hash user_score, for any given user_id, we need to tell # the score of that user, if the user_id key is not present, we need # to return 0 as the scoreuser_score = Hash.new(0)

What does this statement do? It defines a new hash user_score, with a default value 0, which means that for any non-existing key, the hash will return a default value 0

# for any user_id, irrespective of its presence,
# all we need to return is
user_score[user_id]

Enumerable

# We have an array
arr = [1, 2, 3, 4, 5]
# return an array where each ith value is twice the ith value of arr
arr.map { |x| 2 * x }
=> [2, 4, 6, 8, 10]

Now, let’s see if we can use the same method for ruby hash also

# We have a hash h
h = {:a=>1, :b=>2, :c=>3}
# return the list of squared values of hash
h.map { |key, value| value * value }

So far, we have covered one-line solutions for some basic requirements.
Let’s try to answer a bit more complex queries with just one line statements

# We have an array arr
arr = [1, 2, 3, 4, 5]

# return the sum of squares of all elements of the array
# and add 10 to the final answer
arr.inject(10) {|answer, n| answer + (n * n) }
=> 65
# another example
# find the factorial of n = 6
(1..n).inject(1) {|factorial, x| factorial * x}
=> 720

As simple as it looks !!
What we exactly did here?
We are defining a temporary variable answer and initializing it with 10 as we do arr.inject(10),
now inside the block {|answer, n| answer + (n * n) } answer is updated to
answer + (n * n) every time as we iterate over each number n of the array arr

# Lets say we again have our array arr for following examples
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Time for some one-liner boolean checks over the entire array

# checks if any number in the array is even
arr.any? {|a| a.even?}
=> true
arr.reject {|x| x.even?}.any? { |a| a.even?}
=> false
# checks if all elements of the array are even
arr.all? {|a| a.even?}
=> false
arr.select {|x| x.even?}.all? {|a| a.even?}
=> true
# Checks if none of the elements in the array are even
arr.none? {|a| a.even?}
=> false
arr.reject {|x| x.even?}.none? {|a| a.even?}
=> true
# returns the first element divisible by 3 and greater than 3
# and nil if none satisfies the condition
arr.find {|x| (x % 3 == 0 && x > 3) }
=> 6

Grouping elements of array based on some condition

# lets assume we have attendance of users in a hash
attendance = {"ABC" => 80, "PQR" => 40, "DEF" => 14, "XYZ" => 60}
# now, we have some threshold attendance (say 50%),
# only above which we consider a user present
# now, we need to have list of present users under one key "Present"
# and list of absent users under the other key "Absent"
attendance.group_by {|k, v| v >= 50 ? "Present" : "Absent"}
=> {"Present"=>[["ABC", 80], ["XYZ", 60]], "Absent"=>[["PQR", 40], ["DEF", 14]]}

Note: All the examples that I used have very simple conditions, we can always use any complex condition at the same place and still able to deliver the required result in just one line of code.

I hope you enjoyed and learned something new, Thank you

--

--