Home Blog Page 4

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.

How to Use Indention with Multiline Strings with the Squiggly Heredoc Syntax

0

Working with multiline strings in Ruby used to result in very odd looking code because heredocs required that you shift all of the string code so it was flush against the left hand side of the file. However, with modern versions of Ruby you are now able to utilize the squiggly heredoc syntax, which allows you to indent multiline strings in a file.

Summary

Refactor a multiline string in Ruby so that it can be indented.

Exercise File

Code File

Exercise Description

Given a multiline string, stored in a Ruby Heredoc, refactor it so that you can indent the string instead of having it flushed to the left-hand side of the file.

Standard Heredoc Example

<<~EOL
  Some
  words
  in a heredoc
EOL

# Results in:
  Some
  words
  in a heredoc
# Notice the spaces on the left hand side of the text

Required Output

Some
words
in a heredoc

Real World Usage

Working with multiline strings in Ruby used to result in some very odd looking code. Because of fact that heredocs are parsed ‘as is’, it means that you had to place all of the strings all the way to the left of the file. More modern versions of Ruby allow you to indent multiline strings so they can match the rest of the code styles.

Solution

Can be found on the solutions branch on github.

Build a Baseball Scoreboard Program in Ruby

0

This guide examines a seemingly simple program, however, in order to properly implement the solution, you will be required to use a number of key Ruby programming techniques. In this exercise, you’ll build out a scoreboard program that generates an inning by inning score for a baseball team along with a dynamic total.

Summary

Build a program that keeps track of a baseball team’s score on an inning by inning basis along with totaling up the total runs.

Exercise File

Code File

Exercise Description

Build a Ruby class that works like a scoreboard for a 9 inning game. This means that the class should start a game where every inning has 0 runs and as the game goes on, runs can be added to runs, which also changes the total.

Example Game

team = Scoreboard.new('Astros')
team.score # => {"Astros"=>{1=>0, 2=>0, 3=>0, 4=>0, 5=>0, 6=>0, 7=>0, 8=>0, 9=>0}}
team.add_run inning: 3
team.add_run inning: 3
team.add_run inning: 5
team.add_run inning: 8
team.score # => {"Astros"=>{1=>0, 2=>0, 3=>2, 4=>0, 5=>1, 6=>0, 7=>0, 8=>1, 9=>0}}
team.generate_total # => 4

Real World Usage

This may seem like a simple program to build out. However, to properly implement the program to pass all of the tests you will need to work with nested hashes, maintaining value states for data, configure a reader, and perform calculations on nested hash values. This is one of my favorite coding questions to give devs that I’m interviewing since it reveals their knowledge of hashes and how to work with classes.

Solution

Can be found on the solutions branch on github.

Parse a String Based Date and Convert it Into a Ruby Date Object

1

Working with dates in web applications can pose a unique challenge, especially when working with multiple date formats. This guide focuses on how to convert string based strings in a specific format into a Ruby date object so that you can utilize it in your own program.

Summary

Convert a string that contains a date and a specific format into a Ruby date object.

Exercise File

Code File

Exercise Description

Given a string date with the format mm/dd/yyyy, convert the string into a Ruby date object that can be treated like a date created directly in Ruby (meaning that you can perform tasks such as calling methods on it).

Examples

str_date = "07/31/2018"
date_parser(str_date).month # => 7
date_parser(str_date).leap? # => false

Real World Usage

This is a common challenge in modern web applications. Imagine a scenario where you have a jQuery date picker in a Rails application. That date picker is going to send the date as a string in a specific format. Typically the format is one that can’t be properly interpreted by the Rails application. This means that you will need to convert the string and format into a Ruby date object so that it can be used properly.

Solution

Can be found on the solutions branch on github.

A Better Way to Query Hash Values in Ruby

0

Ruby offers a wide variety of solutions for many tasks. In this guide we’re going to explore a more expressive process for querying hashes by leveraging the fetch method.

Summary

Integrate a hash query method that throws an error when asked to query a key that doesn’t exist.

Exercise File

Code File

Exercise Description

The standard hash querying syntax simply returns a nil value when passed a key that doesn’t exist. However this can be confusing because this is the identical behavior to what happens when you query a legitimate key that simply has a nil value. With this in mind, implement a more expressive way to query hashes that will throw an error if the given key does not exist instead of a nil.

Examples

hash = { name: 'Kristine', email: '[email protected]', social: nil }
hash_query(hash, :name) # => 'Kristine'
hash_query(hash, :username) # => Raise KeyError: Key does not exist
hash_query(hash, :social) # => nil

Real World Usage

When working with APIs you will be working with a wide variety of hash values. You will discover that you will be asked to work with collections that contain nil values quite often. If you are using a hash query tool that returns nil for non-existent keys AND for standard nil values, you will waste quite a bit of time trying to figure out the cause of the nil value.

Solution

Can be found on the solutions branch on github.

Using SimpleDelegator in Ruby to Implement the Decorator Pattern

0

There are a number of ways to implement the decorator design pattern in Ruby. In this guide we’re going to examine how we can leverage the SimpleDelegator tool in Ruby to add additional functionality to a class.

Summary

Build a delegator for a Ruby class by using Ruby’s SimpleDelegator.

Exercise File

Code File

Exercise Description

Implement a delegator for a Ruby class using Ruby’s SimpleDelegator process to add functionality to a class without having to add code to the class itself.

Examples

# A standard Ruby class that has a name initializer attribute
invoice = Invoice.new('Kristine Hudgens')

# A decorator that inherits from SimpleDelegator
# and takes in an instance of the Invoice class
decorated_invoice = InvoiceDecorator.new(invoice)

# invoice_month needs to be a method in the class
# but it can be called by the delegate
decorated_invoice.invoice_month # => 9

# last_name is a method in the decorator
# that splits the class name attribute
decorated_invoice.last_name # 'Hudgens'

# this shows that you can access the object
# passed to the decorator with the __getobj__ method
decorated_invoice.__getobj__ == invoice # => true

Real World Usage

The decorator pattern is a common design pattern. Ruby offers a number of processes for implementing the pattern and the SimpleDelegator is one of the most popular. This is critical when it comes to building clean programs and following best practices.

Solution

Can be found on the solutions branch on github.

Utilizing the Phone Gem to Create, Format, and Query Phone Numbers

0

Working with phone numbers, especially for International applications, can be a challenging task. In this guide we’re going to walk through how to implement the popular Phone RubyGem in order to create, format, and work with phone numbers in a Ruby program.

Summary

Implement the Phone RubyGem in order to work with phone numbers.

Exercise File

Code File

Exercise Description

Work with the Phone RubyGem code library in order to build four methods. The methods should be able to properly:

  • Build a phone number object.
  • Query a phone number for separate components, such as area code and extension.
  • Format a phone number object to match the style (123) 456-7890.
  • Check to see if a phone number is valid.

Four Examples

phone = phone_builder(number: '1234567',
                          area_code: '480',
                          country_code: '1',
                          extension: '333')
phone.area_code # => '480'

phone_parser('+16021234567').area_code # => '602'

phone_formatter '+16021234567' # => '(602) 123-4567'

phone_valid? '+16021234567' # => true

Research the Phone gem. Each of these method calls can be built by simply calling modules and methods from the gem.

Real World Usage

Working with phone numbers can be incredibly complex when you consider all of the edge cases associated with tasks such as: extracting area codes for International numbers, working with dynamically sized phone extensions, etc. I have received multiple questions from students asking for the best way to work with phone numbers in Ruby and so I wanted to build a guide completely dedicated to the topic.

Solution

Can be found on the solutions branch on github.

Use attr_extras Gem to Refactor a Ruby Class

0

This guide examines how to streamline a class definition in Ruby by using the attr_extras Ruby gem. This gem allows you to remove unnecessary boilerplate code when you define attributes in Ruby.

Summary

Refactor a Ruby class so that it uses the attr_extras gem.

Exercise File

Code File

Exercise Description

Clean up how Ruby defines its list of attributes by leveraging the attr_extras gem. This will allow you to remove unnecessary boilerplate code when listing attributes.

Class to Refactor

class PurchaseOrder
  attr_accessor :client, :total

  def initialize(client, total)
    @client = client
    @total = total
  end

  def generate_order
    "#{client}: #{total}"
  end
end

po = PurchaseOrder.new('Google', 500)
po.client # => 'Google'
po.generate_order # => 'Google: 500'

Research the attr_extras gem to see how you can streamline this class and remove the initialize method.

Real World Usage

Ruby is an intuitive programming language. It allows you to skip quite a bit of boilerplate code. For example, in Ruby you won’t have to write class setters and getters manually. However there are still a few processes that you will find yourself repeating on a regular basis. The attr_extras gem is a great tool to help you streamline how you define attributes in a class.

Solution

Can be found on the solutions branch on github.

Build a Progress Tracking Class in Ruby

0

This guide walks through how to implement a progress tracking class in Ruby that can update a user’s progress and dynamically update the overall percent completed.

Summary

Implement a class that tracks a user’s completion percentage and dynamically allows a user to update it.

Exercise File

Code File

Exercise Description

Build a class that tracks the completed percentage of a course for a student, and when the student marks a task complete, the class should update the percent complete to reflect the updated value.

Example Workflow

c = Completion.new(number_of_guides: 100, total_completed: 55)
c.completed_percentage # => 0.55

c.mark_complete

c.completed_percentage # => 0.56

Real World Usage

Tracking progress and dynamically updating values is a common process in Ruby development. This exercise will test your ability to build a class, work with data in the class, and generate different outcomes based on method calls.

Solution

Can be found on the solutions branch on github.

Integrate a Helper Module in Ruby

0

This guide walks through how to integrate Ruby modules in order to add custom helper methods to a class.

Summary

Build a module with helper methods and call the methods from a class.

Exercise File

Code File

Exercise Description

Build a helper module called InvoiceHelper that contains a method called taxable? that checks the source of an order and returns if it’s taxable order or not. Then build a class called Sale that has a total and source attribute. Then build a method called place_order that returns the total plus a 6% tax rate if the source is AZ or online, and returns the total by itself if the source is any other value.

Example Input

s = Sale.new(500, 'AZ')
s.place_order # => 530.0

s2 = Sale.new(500, 'TX')
s2.place_order # => 500.0

Real World Usage

Building helper modules is an important task when it comes to code organization. This example is a practical case study on how you can add a boolean helper method to a class without having to clutter the class code.

Solution

Can be found on the solutions branch on github.