DEV Community

Alana Edwards
Alana Edwards

Posted on

TIL: Today I Learned Ruby Shortcuts

Shortcuts make life easier!

Of course the journey is rewarding and necessary but if you can get to your destination just a little bit quicker, shortcuts can definitely help you while you're on your way. This is my personal journey towards becoming a Fullstack developer and video game developer so buckle up and enjoy the ride while I take you to the latest stop: Shortcuts

Today I learned two syntactic sugar Ruby methods from a TA(John) that helped me with my module assignments. One of them being the .keys method and the other the .is_a? method.

In this first example:

elsif some_random_input == { :city => "Chicago", :state => "IL", :zip => 60654 }
pp some_random_input.keys

I wanted to access and print just the keys

:city, :state, :zip

from this Hash. I was able to quickly output all of the keys in the Hash using the .keys method.

In the second example:

elsif some_random_input.is_a?(Time)
pp some_random_input.strftime("%A").downcase

I wanted to print the day "Monday" in lower case from the Time.now object. Instead of writing a longer if statement I used the .is_a? method which returned the correct value based on the object's class Time. This method saves us time and condenses the code.

Top comments (0)