Phone

+123-456-7890

Email

[email protected]

Opening Hours

Mon - Fri: 7AM - 7PM

Are you looking to expand your knowledge of Ruby and learn new tricks, patterns, and methods? One of the best ways to do so is by reading code written by other developers. But where can you find interesting code that is worth reading? In this article, we have compiled seven examples of Ruby code that we believe you will find both interesting and educational. Along with each example, we will provide commentary to help you gain a deeper understanding of the code. So let’s dive in and explore these fascinating Ruby code examples!

Sum Of Two Numbers

The first example we will be looking at is a method that checks if there is a combination of two numbers in an array that adds up to a target number. This is a common problem that often arises in coding challenges and interviews. The code for this method is as follows:

def sum_eq_n?(arr, n)

  return true if arr.empty? && n == 0

  arr.product(arr).reject { |a,b| a == b }.any? { |a,b| a + b == n }

end

This method uses the product method, which is similar to having a loop inside a loop that combines all values in array A with all values in array B. We then use reject to remove any pairs of numbers that are the same, as we only want unique combinations. Finally, we use any? to check if any of the remaining pairs add up to the target number. If so, the method returns true, otherwise it returns false.

Explanation

Let’s break down the code and understand what each line does. The first line defines our method sum_eq_n? and takes in two parameters: arr which is an array of numbers, and nwhich is the target number we want to check for. The second line is a guard clause that checks if the array is empty and if the target number is 0. If both conditions are met, the method returns true immediately.

The third line is where things get interesting. We use the product method on the array, which creates an array of all possible combinations of elements from the original array. For example, if our array is [1,2,3], the product method will return [[1,1], [1,2], [1,3], [2,1], [2,2], [2,3], [3,1], [3,2], [3,3]]. This is essentially like having a nested loop that combines each element with every other element in the array.

Next, we use reject to remove any pairs of numbers that are the same, as we only want unique combinations. This is done by passing a block to reject that checks if the two elements are equal. Finally, we use any? to check if any of the remaining pairs add up to the target number n. If so, the method returns true, otherwise it returns false.

Counting, Mapping & Finding

In this example, we will be looking at a strategy for finding the missing number in an arithmetic sequence. For example, if we have the sequence (2,4,6,10), we can use this strategy to determine that the missing number is 8. Let’s take a look at the code:

differences = [2, 2, 4]

differences.max_by { |n| differences.count(n) }

Explanation

The first line of code creates an array called differences that contains the differences between each consecutive pair of numbers in the sequence. In our example, the differences would be [2, 2, 4]. The goal of this code is to find out what the sequence is and how it is increasing or decreasing. We do this by finding the most common difference in the array.

The second line uses the max_by method, which takes a block as an argument and returns the element that has the maximum value after running the block on each element. In our case, we pass in differences.count(n) as the block, which counts the number of times each element appears in the array. This means that the element with the highest count will be returned, which in this case is 2. This tells us that the sequence is increasing by 2 each time.

Programming background with person working with codes on computer

Regular Expression Example

Regular expressions are a powerful tool for pattern matching and string manipulation. In this example, we will look at a simple regular expression that checks if a string contains only letters and spaces. Here is the code:

def letters_and_spaces_only?(str)

  str.match?(/\A[a-zA-Z\s]+\z/)

end

Explanation

The first line defines our method letters_and_spaces_only? which takes in a string as a parameter. The second line uses the match? method, which checks if the given string matches the regular expression \A[a-zA-Z\s]+\z. Let’s break down this regular expression:

  • \A matches the beginning of the string;
  • [a-zA-Z] matches any letter from a to z, both lowercase and uppercase;
  • \s matches any whitespace character;
  • + matches one or more occurrences of the previous character;
  • \z matches the end of the string.

This regular expression essentially checks if the entire string consists of only letters and spaces. If it does, the method returns true, otherwise it returns false.

Recursion & Stack Example

Recursion is a technique where a method calls itself until a certain condition is met. In this example, we will look at a recursive method that calculates the factorial of a given number. Here is the code:

def factorial(n)

  return 1 if n == 0

  n * factorial(n-1)

end

Explanation

The first line defines our method factorial which takes in a number as a parameter. The second line is a guard clause that checks if the number is 0. If so, the method returns 1 immediately. This is because the factorial of 0 is defined as 1.

The third line is where the recursion happens. We call the factorial method again, passing in n-1 as the argument. This means that the method will keep calling itself with progressively smaller values of n until it reaches 0. At this point, the recursion stops and the method starts returning values back up the stack. For example, if we call factorial(5), the method will call itself with 4, then 3, then 2, then 1, and finally 0. Once it reaches 0, it will start returning values back up the stack, multiplying each value by the previous one until it reaches 5. This results in the factorial of 5, which is 120.

Method Chaining Example

Method chaining is a technique where multiple methods are called on the same object in a single line of code. It can make your code more concise and readable. In this example, we will look at how we can use method chaining to manipulate an array of strings. Here is the code:

names = ["John", "Jane", "Jack"]

names.map(&:downcase).select { |name| name.start_with?("j") }.sort

Explanation

The first line creates an array of strings called names. The second line uses the map method to iterate through each element in the array and call the downcase method on it. This converts all the names to lowercase. Next, we use the select method to filter out any names that do not start with the letter “j”. Finally, we use the sort method to sort the remaining names alphabetically. All of this is done in a single line of code thanks to method chaining.

Developer works on data center on laptop

With Index Example

In Ruby, the each_with_index method allows us to iterate through an array and access both the element and its index at the same time. In this example, we will look at how we can use this method to manipulate an array of numbers. Here is the code:

numbers = [1, 2, 3, 4, 5]

numbers.each_with_index { |num, index| numbers[index] = num * 2 }

Explanation

The first line creates an array of numbers called numbers. The second line uses the each_with_index method to iterate through the array and access both the element and its index. We then use the index to update the value of the element by multiplying it by 2. This results in the array being modified to [2, 4, 6, 8, 10].

Each With Object Example

Similar to each_with_index, the each_with_object method allows us to iterate through an array and access both the element and an object at the same time. In this example, we will look at how we can use this method to count the number of occurrences of each element in an array. Here is the code:

fruits = ["apple", "banana", "orange", "apple", "grape", "banana"]

fruits.each_with_object(Hash.new(0)) { |fruit, counts| counts[fruit] += 1 }

Explanation

The first line creates an array of fruits called fruits. The second line uses the each_with_object method to iterate through the array and access both the element and a hash object. We use Hash.new(0) to create a new hash with a default value of 0. This means that if we try to access a key that does not exist in the hash, it will return 0 instead of nil.

Inside the block, we use the current fruit as the key and increment its value by 1. This results in the hash containing the count of each fruit, which is { “apple” => 2, “banana” => 2, “orange” => 1, “grape” => 1 }.

Summary

In this article, we have explored seven interesting Ruby code examples that cover a range of topics such as array manipulation, regular expressions, recursion, method chaining, and more. Each example has been accompanied by an explanation to help you understand the code better. By studying and experimenting with these examples, you can expand your knowledge of Ruby and improve your coding skills.

Recommended Articles

Leave A Comment