DEV Community

Nezir Zahirovic
Nezir Zahirovic

Posted on

10 Useful Ruby One-Liners: Examples and Descriptions

Introduction:

Ruby is a powerful and elegant programming language known for its readability and expressiveness. One-liners, concise lines of code that perform a specific task, are particularly popular among Ruby developers for their simplicity and efficiency. In this blog post, we will explore 10 of the most useful Ruby one-liners, complete with examples and detailed descriptions of their functionality. Whether you're a beginner or an experienced Ruby programmer, these handy code snippets are sure to enhance your productivity and make your coding journey smoother.

Count the Occurrence of Elements in an Array:

array = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] 
result = array.group_by(&:itself).transform_values(&:count) 
Enter fullscreen mode Exit fullscreen mode

This one-liner uses group_by and transform_values methods to count the occurrence of each element in the array. The result will be a hash with elements as keys and their corresponding counts as values.

Sum of All Elements in an Array:

array = [1, 2, 3, 4, 5] 
result = array.inject(:+)
Enter fullscreen mode Exit fullscreen mode

By utilizing the inject method with the :+ symbol, this one-liner calculates the sum of all elements in the array.

Find the Maximum Value in an Array:

array = [5, 9, 2, 7, 1] 
result = array.max 
Enter fullscreen mode Exit fullscreen mode

With the help of the max method, this one-liner quickly identifies the maximum value present in the array.

Reverse a String:

string = "Hello, World!" 
result = string.reverse 
Enter fullscreen mode Exit fullscreen mode

This simple one-liner employs the reverse method to reverse the characters in a given string.

Check if a String is a Palindrome:

string = "level" 
result = string == string.reverse 
Enter fullscreen mode Exit fullscreen mode

By comparing a string with its reversed form, this one-liner determines if the string is a palindrome or not.

Remove Duplicates from an Array:

array = [1, 2, 2, 3, 4, 4, 5] 
result = array.uniq 
Enter fullscreen mode Exit fullscreen mode

Using the uniq method, this one-liner removes duplicate elements from an array, leaving only the unique values.

Flatten a Nested Array:

nested_array = [[1, 2], [3, 4], [5, 6]] 
result = nested_array.flatten 
Enter fullscreen mode Exit fullscreen mode

This one-liner utilizes the flatten method to transform a nested array into a single-dimensional array.

Sort an Array in Ascending Order:

array = [5, 2, 7, 1, 4] 
result = array.sort 
Enter fullscreen mode Exit fullscreen mode

By employing the sort method, this one-liner arranges the elements of an array in ascending order.

Calculate the Factorial of a Number:

number = 5 
result = (1..number).inject(:*) || 1
Enter fullscreen mode Exit fullscreen mode

Using the inject method with the :* symbol, this one-liner calculates the factorial of a given number.

Find the Average of Values in an Array:

array = [3, 6, 9, 12, 15] 
result = array.sum / array.size.to_f 
Enter fullscreen mode Exit fullscreen mode

This one-liner calculates the average of values in an array by dividing the sum of the array elements by its size, ensuring a floating-point result.

Double the Values in an Array:

array = [1, 2, 3, 4, 5] 
result = array.map { |num| num * 2 } 
Enter fullscreen mode Exit fullscreen mode

In this one-liner, the map method is used to iterate over each element in the array and double its value. The resulting array will contain the doubled values.

Convert Strings to Uppercase:

strings = ["hello", "world", "ruby"] 
result = strings.map(&:upcase) 
Enter fullscreen mode Exit fullscreen mode

By utilizing the map method with the &:upcase syntax, this one-liner converts each string in the array to uppercase. The resulting array will contain the uppercase versions of the original strings.

Extract Specific Attributes from an Array of Objects:

class Person attr_accessor :name, :age 
  def initialize(name, age) 
    @name = name 
    @age = age 
  end  
end 
Enter fullscreen mode Exit fullscreen mode
people = [Person.new("Alice", 25), Person.new("Bob", 30), Person.new("Charlie", 35)] 
result = people.map(&:name) 
Enter fullscreen mode Exit fullscreen mode

In this example, we have a class Person with attributes name and age. The map method is used to extract only the name attribute from each object in the people array. The resulting array will contain the names of all the people.

These examples showcase the versatility of the map method, allowing you to transform and manipulate data in a concise and elegant manner. Feel free to experiment with map and adapt these one-liners to suit your specific use cases.
More about Ruby On Rails in my latest book|
The Ruby On Rails Interview Bible 2023

Conclusion:
Ruby one-liners are an excellent way to simplify your code and achieve concise solutions to various programming challenges. In this blog post, we explored 10 of the most useful Ruby one-liners, providing examples and detailed descriptions for each. By leveraging these powerful snippets, you can enhance your Ruby programming skills and boost your productivity. Remember to experiment and adapt these one-liners to suit your specific needs, and enjoy the elegance and efficiency of Ruby coding.
Happy coding!

Top comments (3)

Collapse
 
phi profile image
Pascal Hurni

Hi,
Your first example Count the Occurrence of Elements in an Array may be rewritten much simplier like this:

result = array.tally

Cheers

Collapse
 
nezirzahirovic profile image
Nezir Zahirovic

thats great, thank you!

Collapse
 
nezirzahirovic profile image
Nezir Zahirovic

Short article with samples of ruby onliners.