Home Blog Page 3

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.

Build a File Type Hash Mapper in Ruby

0

Whether it’s a complex coding interview question or algorithm implementation, there are many times where you will be asked to combine a large number of processes into a single feature. In this guide we’ll examine how to build a non-trivial program that takes in an array of file names and generates a hash collection where each file type is the key and the value is an array of their respective file names.

Summary

Build a method that takes in an array of file names and filters them into an organized hash.

Exercise File

Code File

Exercise Description

Given an array of file names (with file extensions), build a method that splits the array into a hash where the keys are the file types and the values are arrays that contain the file name.

Example

file_names = %w{file1.rb file2.html file3.rb file4.rb file5.js}

# Result should be:
{
  'rb' => ['file1', 'file3', 'file4'],
  'html' => ['file2'],
  'js' => ['file5']
}

Real World Usage

This is a non-trivial exercise. In order to properly implement this solution you will need to utilize the following valuable skills:

  • Opening up the Array class and adding a custom method
  • Iterating over an array and dynamically building a hash with default empty arrays for each of the values
  • Working with custom File methods
  • Implement string parsing methods to clean up output

Solution

Can be found on the solutions branch on github.

Build an Array Method that Returns a List of Filenames for Specific File Types

0

Parsing file types can be a complex process. However, by leveraging the grep method you can leverage regular expressions to quickly return a full list of all of the file types that you’re searching for.

Summary

Build a method that searches for specific file types.

Exercise File

Code File

Exercise Description

Add a method to the Array class that can look through an array of file names and return a filtered array with the file names for the file type searched for.

Example

file_names = %w{file1.rb file2.html file3.rb file4.rb file5.js}
file_names.file_selector 'rb' # => ['file1', 'file3', 'file4']

Real World Usage

Ruby provides developers a number of options when it comes to implementing solutions. As a dev, one of the daily tasks that you’ll have is to work through various solutions to find the one that works the best for your particular program. There were multiple ways to solve this exercise and being able to experiment with what makes one solution a better fit than another is important. Additionally, if you implemented the solution that I utilized, you will have also worked with: regular expressions and Unix command tools.

Solution

Can be found on the solutions branch on github.

Remove Anomalies in a Ruby Array

0

When working with large data sets, you’ll discover that there are many times where your collections have anomalies that need to be removed. In this guide we’ll walk through how to easily remove any values lower or higher than a range of values.

Summary

Implement the ability to remove anomalies from a Ruby collection

Exercise File

Code File

Exercise Description

Given an array of integers, add a method to the array class that removes any/all values higher or lower than specified arguments.

Standard Heredoc Example

[44, 8043, 443, 43452, 2183].remove_anomalies 100, 10_000 # => [8043, 443, 2183]

Real World Usage

When working with machine learning algorithms, one of the key requirements is to clean up the data and remove anomalies. Imagine a situation where you are building a baseball statistic algorithm and you want to ignore players who only played in a few games to ensure that you are only looking at data from a typical player. In this guide, we focused on how to leverage a helpful Ruby method that allows you to quickly return only the data that you need.

Solution

Can be found on the solutions branch on github.