Home Blog Page 3

How to Find All Duplicates in an Array in Ruby

1

Ruby has a helpful method for removing duplicates from an array, the uniq method. However, there are times when you simply want to know which elements in an array are duplicates. In this guide we’ll add a method to the Array class that returns all duplicates.

Summary

Build a method that returns all of the duplicates from an array in Ruby.

Exercise File

Code File

Exercise Description

Add a new method to Ruby’s Array class that returns all duplicate values.

Example Input/Output

ints = [1, 2, 1, 4]
ints.find_duplicates # => [1]

invoices = [
  { company: 'Google', amount: 500, date: Date.new(2017, 01, 01).to_s, employee: 'Jon Snow' },
  { company: 'Yahoo',  amount: 500, date: Date.new(2017, 01, 01).to_s, employee: 'Jon Snow' },
  { company: 'Google', amount: 500, date: Date.new(2015, 07, 31).to_s, employee: 'Jon Snow' },
  { company: 'Google', amount: 500, date: Date.new(2017, 01, 01).to_s, employee: 'Jon Snow' },
  { company: 'Google', amount: 500, date: Date.new(2017, 01, 01).to_s, employee: 'Jon Snow' },
  { company: 'Google', amount: 500, date: Date.new(2017, 01, 01).to_s, employee: 'Jon Snow', notes: 'Some notes' },
  { company: 'Google', amount: 500, date: Date.new(2017, 01, 01).to_s, employee: 'Jon Snow', notes: 'Some notes' },
]

invoices.find_duplicates

# => [
# =>   {:company=>"Google", :amount=>500, :date=>'2017-01-01', :employee=>"Jon Snow"},
# =>   {:company=>"Google", :amount=>500, :date=>'2017-01-01', :employee=>"Jon Snow"},
# =>   {:company=>"Google", :amount=>500, :date=>'2017-01-01', :employee=>"Jon Snow", :notes=>"Some notes"}
# => ]

Real World Usage

I got the idea for this exercise when I accidentally submitted a duplicate expense into Freshbooks and the system did a great job in letting me know that I may have a potential duplicate expense. Additionally, Ruby has a very helpful Array class method, uniq, that removes all duplicates from an array. However, Ruby doesn’t have a simple way to find all duplicates in a collection, so this will help you examine how to parse through arrays efficiently to return all of the duplicate values.

Solution

Can be found on the solutions branch on github.

Build Rock, Paper, Scissors in Ruby with Player vs Computer Gameplay

0

Rock, paper, scissors may seem like a simple game to build, however it offers a great base case for how to build a rule’s engine that can be scaled up for more complex systems. In this guide we’ll examine how to build the game so that users can play against the computer.

Summary

Develop a Rock, Paper, Scissors game that allows users to play against the computer.

Exercise File

Code File

Exercise Description

Build a game class that allows users to guess rock, paper, or scissors. Additionally, build a method that generates a random guess from the computer. Finally, pass both guesses through a rule’s engine to return who is the winner of the game is. Focus on building a rule’s engine that could scale to other rules instead of simply creating a large conditional.

Example Input/Output

# Examples below assume the computer guesses 'paper'

rps = RPS.new(guess: 'rock')
rps.winner_is # => 'Computer wins'

rps = RPS.new(guess: 'Scissors')
rps.winner_is # => 'You win!'

rps = RPS.new(guess: 'paper')
rps.winner_is # => 'Tie'

Real World Usage

This is a popular coding interview question, not because it’s overly complex, but because it allows you to demonstrate your problem solving ability, especially as it relates to code flexibility. If you were to build this game and the rule’s engine was comprised of a long set of conditionals, as soon as new rules were added to the game, the program would become convoluted and difficult to alter. However if you properly separate the game concerns it becomes easier to manage.

Solution

Can be found on the solutions branch on github.

Build a Dice Validator in Ruby

0

Building validations in programs is a common requirement. In this exercise we’ll examine how to ensure a set of dice are valid by implementing a method that returns false if the dice are outside the range of 1-6.

Summary

Build a dice validator program.

Exercise File

Code File

Exercise Description

Implement a program that checks to see if a roll of two dice is valid or not.

Example Input/Output

valid_dice? 4, 2 # => true
valid_dice? 6, 6 # => true
valid_dice? 5, 1 # => true
valid_dice? 8, 2 # => false
valid_dice? 1, 7 # => false
valid_dice? 9, 7 # => false

Real World Usage

Working with range based validations are a common requirement for a wide variety of applications. Imagine a situation where you need to see if a user’s zip code falls inside of a certain range of numbers. There are a number of ways to implement this solution, I personally opted for the version that worked with collections of data.

Solution

Can be found on the solutions branch on github.

Build a Prefix Notation Calculator in Ruby

0

Building a calculator is a popular interview question and a good approach for learning a programming language. In this guide we’re going to build a Prefix Notation calculator in Ruby, which enables users to enter an operator, followed by any set of numbers to calculate.

Summary

Build a Prefix Notation Calculator in Ruby.

Exercise File

Code File

Exercise Description

Build a method that performs addition, subtraction, multiplication, and division on any number of values passed to the method. Additionally, ensure to handle improperly entered requests (bonus points if you build your own error handling class).

Real World Usage

This is a popular interview coding question since it requires developers to showcase skill when it comes to working with mathematical calculations in Ruby. Additionally, it offers a number of potential implementation options, including a wide range of options when it comes to managing improper input from users.

Solution

Can be found on the solutions branch on github.

Pass Multiple Blocks to a Method by Leveraging Lambdas in Ruby

0

In many cases, lambdas are the most effective when they’re used in conjunction with methods. A method is limited to taking a single block in Ruby, however by leveraging lambdas you are able to pass in as many blocks as needed.

Summary

Implement a method that can accept multiple blocks by leveraging lambdas.

Exercise File

Code File

Exercise Description

Build a method that takes multiple lambdas as arguments in order to illustrate how a single method can be passed multiple blocks as arguments.

Real World Usage

By default, a method in Ruby is limited to only receiving a single block as an argument. This is where lambdas (also known as closures in other languages) are able to extend the functionality of a single method. A method can take an unlimited number of lambdas as argument, so therefore lambdas allow you to give plain Ruby methods the ability to accept multiple blocks as arguments. This exercise helps to showcase this behavior by building a User tracking solution.

Solution

Can be found on the solutions branch on github.

Procs and Lambdas vs Methods for Variable Scope in Ruby

2

There are some key differences between procs / lambdas and traditional methods in Ruby, however the differences can many times be subtle. In this exercise we’ll examine how variable scope is processed differently between the different options.

Summary

Build a program that illustrates the differences in variable scope in Ruby between Procs / Lambdas, and traditional methods.

Exercise File

Code File

Exercise Description

Build a traditional method and a lambda or Proc and illustrate how the two processes have different access levels for local variables.

Real World Usage

This exercise showcases one of the subtle differences between Procs / lambdas and plain Ruby methods. At a high level it may seem like the three options can be used interchangeably, however in this guide we’ll walk through how they approach variable access much differently.

Solution

Can be found on the solutions branch on github.

Refactoring an Iterative XML Parser to Use Functional Programming in Ruby

0

In the last guide I implemented an XML parser that counted all of the lines from Shakespeare’s Macbeth play. That implementation worked, however it used an iterative approach, which resulted in a highly coupled method that would only be able to work on another XML file if it had an identical structure and set of tag names. In this guide we’re going to refactor the solution to utilize a functional approach.

Summary

Refactor the Macbeth XML parser/counter so it uses a functional programming approach.

Credit to Upcase for the great coding exercise.

Exercise File

Code File

Exercise Description

Split the macbeth_parser method into multiple methods that utilize functional programming calls instead of the iterative approach. The RSpec tests should still pass, which means that the resulting output should be identical to the current implementation.

Real World Usage

This solution was more challenging to build out than the iterative approach. However the result will be a more scalable implementation that can be utilized by other XML files. Anytime that you are building a program, it’s typically a good idea (and a good practice) to design with modularity in mind.

Solution

Can be found on the solutions branch on github.

How to Sum XML Data and Converting it to a Hash in Ruby

0

When it comes to working with APIs, two of the most common tools that you will use are JSON and XML. In this guide we’ll walk through a challenging task in which we ingest the full play of Shakespeare’s Macbeth in XML and convert it into a hash that sums the total number of lines for each character in the play.

Credit to Upcase for the great coding exercise.

Summary

Build out a method that sums the total number of lines of each character in Macbeth.

Exercise File

Code File

Exercise Description

Implement a method that parses Shakespeare’s Macbeth play (stored in XML). The method should return a hash, with the key being the name of the character and the value being the total number of lines the character had.

If you fork the coding exercise repo you can access the XML data in the support directory.

For reference, here is the XML source data.

Example

macbeth_counter['ROSS'] # => 135
macbeth_counter['FLEANCE'] # => 2

macbeth_counter

# Full hash return value
{
  "First Witch"=>62,
  "Second Witch"=>27,
  "Third Witch"=>27,
  "ALL"=>24,
  "DUNCAN"=>70,
  "MALCOLM"=>212,
  "Sergeant"=>35,
  "LENNOX"=>73,
  "ROSS"=>135,
  "MACBETH"=>718,
  "BANQUO"=>113,
  "ANGUS"=>21,
  "LADY MACBETH"=>265,
  "Messenger"=>23,
  "FLEANCE"=>2,
  "Porter"=>46,
  "MACDUFF"=>180,
  ["MACBETH", "LENNOX"]=>1,
  "DONALBAIN"=>10,
  "Old Man"=>11,
  "ATTENDANT"=>1,
  "First Murderer"=>30,
  "Second Murderer"=>15,
  "Both Murderers"=>2,
  "Servant"=>5,
  "Third Murderer"=>8,
  "Lords"=>3,
  "HECATE"=>39,
  "Lord"=>21,
  "First Apparition"=>2,
  "Second Apparition"=>4,
  "Third Apparition"=>5,
  "LADY MACDUFF"=>41,
  "Son"=>20,
  "Doctor"=>45,
  "Gentlewoman"=>23,
  "MENTEITH"=>12,
  "CAITHNESS"=>11,
  "SEYTON"=>5,
  "SIWARD"=>30,
  "Soldiers"=>1,
  "YOUNG SIWARD"=>7
}

Real World Usage

If you struggle with this exercise, don’t be discouraged. This is not a trivial coding exercise. There are a number of ways to implement this solution, and in fact in the next guide I’m going to show an alternative solution that refactors the solution and utilizes a functional approach. To properly build this program you will need to be able to:

  • Parse XML data
  • Convert XML data into a hash data structure
  • Worked with multiple nested iterators
  • Perform calculations on dynamic data

Solution

Can be found on the solutions branch on github.

Convert an Array of File Require Statements into File Names

0

When building scripts, it’s a common requirement to remove and update multiple items in a collection of strings. In this guide we’re going to mimic the process needed to take a list of require statements and generate a list of file names.

Summary

Implement a method that generates a list of file names based on a collection of require statements.

Exercise File

Code File

Exercise Description

Build a method that takes in an array of require statements and outputs an array of the file names with their JavaScript extension added.

Example

javascript_files = [
  '//= require custom/scripts',
  '//= require base/defaults',
  '//= require html.sortable',
  '//= require moment',
  '//= require test-styles'
]

append_js_file_extension javascript_files

# Output
[
  'custom/scripts.js',
  'base/defaults.js',
  'html.sortable.js',
  'moment.js',
  'test-styles.js'
]

Real World Usage

Imagine that you were asked to build a feature that took in the contents of a file and you had to both remove and add content for each array element. This is a common requirement for tasks such as: building file parsers, developing view helper methods, and many more features.

Solution

Can be found on the solutions branch on github.

Working with Infinity in Ruby

0

Working with infinity can be a unique challenge in many different programming languages. Thankfully Ruby offers a helpful library that allows you to implement infinity into programs, and that’s what this guide focuses on.

Summary

Build a method that utilizes infinity in order to generate a string based collection of any size.

Exercise File

Code File

Exercise Description

Leverage Ruby’s Infinity library in order to build a method that generates a collection of string based integers of any size provided by the method argument.

Example

string_infinity_generator 10 # => ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
string_infinity_generator 2 # => ["1", "2"]
string_infinity_generator 20000 # => ["1", "2", ..., "20000"]

Real World Usage

Technically this particular coding exercise could be built by leveraging ranges, which is the common convention. However, there are times, especially when working with mathematical equations that you will discover the need to implement the concept of infinity.

Solution

Can be found on the solutions branch on github.