blake.app

Ruby

This is a work in progress, but I figured I might as well get started. Here is a list of Ruby things that I’ve found helpful.

Rename a hash key

hash[:new_key] = hash.delete :old_key

source

Ensure a Ruby hash is only using symbols

This will convert the hash keys to symbols instead of them being strings.

hash.symbolize_keys!

source

Get the first X characters of a string

"123456789"[0..4]
# "12345"

But this can be a better way

"123456789".first(5)
# "12345"

especially if you are storing the string length as a constant like this:

MAX = 5
"123456789".first(MAX)
# "12345"

Subtracting Days in Ruby

I need a unix timestamp for a specific day. You can do that with .to_i on the Time class, but not with Date

Time.now.to_i
# 1632854844

I also need the unix epoch for different dates, so what I can do is subtract days (in seconds) from Time.now

Time.now
# 2021-09-28 12:43:10.3599796 -0600

Time.now - 1 # Don't do this
# 2021-09-28 12:43:17.6062736 -0600

Time.now - 1*24*60*60 # (1 Day ago)
# 2021-09-27 12:43:57.8495587 -0600

Time.now - 2*24*60*60 # (2 Days ago)
# 2021-09-26 12:44:05.9715538 -0600

(Time.now - 3*24*60*60).to_i # (3 Days ago to Unix Epoch)
# 1632595460

source

Zero?

As a better alternative to a.count == 0 use .zero?

a.count.zero?
# true

Remove array element at index

You can use .slice!(index) to remove a specific element from an array.

arr = ['a', 2, 'b']
# ["a", 2, "b"]
arr.slice!(1)
# 2
arr
# ["a", "b"]