Ruby Send Method

I have spent the last two weeks completing my first project at Flatiron School and the Ruby Send method became a lifesaver for me. For the project, we were tasked with building a Ruby gem that uses a CLI to give a user access to some sort of data. This could be done via scraping, or accessing an API.

As an avid hockey fan, I decided to create a program that would access an API that contained data on all NHL teams. This included their record, offensive and defensive statistics, as well as special teams statistics and more. The program displays all of the teams in the National Hockey League, and then asks the user to choose a team. The user is then given a list of statistical categories to choose from, and once chosen, the statistics for the selected team are displayed.

I created an API class that would handle the call for the API, and a CLI class. On top of these classes, I created a Team class that would initialize a team when given a hash that contained various key value pairs that held information about that specific team.

This is where the Send method came into play. The send method of Ruby is an extremely valuable tool for mass assignment. This method allows you to initialize an object with a hash, and then sets each key of the hash to an attribute, and each value of the hash to the attribute value. See the example below:

This means that if you were to call ‘ ‘ the return value would be “Sharks” and if you were to call ‘ hash.wins ‘ the return value would be 40. This allowed me to initialize an object with a hash that corresponded to a specific team in the NHL. The send method was then used, and the keys of the hash were turned into attributes.

The Ruby send method is one of many methods that is given to us from Ruby and one of the reasons that this method is so valuable is because it allows us to to create a varying amount of attributes from a hash without having to “hard-code” it.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store