My Ruby Cheat Sheet

Kevin FOO
2 min readSep 13, 2021

The disadvantage of coding in multiple languages at the same time is that you tend to mix up which function is for which language. I had to google for the same function over and over again.

It is time start my own cheat sheet and append more into it over time.

String

Concatenate string

name = 'Bitcoin'
price = 42000
puts name+ ' is now USD ' + price.to_s # Bitcoin is now USD 42000
puts "#{name} is now USD #{price}" # Bitcoin is now USD 42000
puts '%s is now USD %d' % [name,price] # Bitcoin is now USD 42000

Detect char/word in string

s='hello world'
puts s.index('z') #
puts s.include? 'z' # false
puts s.index('o') # 4
puts s.include? 'o' # true

Get variable type

a = ['apple','pear']
s = 'kiwi'
h = {'fruit'=>'orange'}
puts a.class # Array
puts s.class # String
puts h.class # Hash

Date & Time

Date string format

require 'time'
t = Time.parse('Mon Jan 2 15:04:05 MST 2006')
puts t.strftime('%Y-%m-%d %H:%M:%S') # 2006-01-02 15:04:05

Commonly used formatting options.

%B    LongMonth    "January"
%b Month "Jan"
%-m NumMonth "1"
%m ZeroMonth "01"
%A LongWeekDay "Monday"
%a WeekDay "Mon"
%e Day "2"
%d ZeroDay "02"
%k Hour "15"
%H ZeroHour "15"
%l Hour12 "3"
%I ZeroHour12 "03"
%-M Minute "4"
%M ZeroMinute "04"
%-S Second "5"
%S ZeroSecond "05"
%Y LongYear "2006"
%y Year "06"
%p PM "PM"
%P pm "pm"
%Z TZ "UTC"

Timezone conversion

require 'date'
dt = DateTime.parse('Mon Jan 2 15:04:05 MST 2006')
utc = dt.new_offset('+00:00') # 2006-01-02T22:04:05+00:00

File

Read entire file content into variable

f = File.read('temp.txt')
puts f
#
# or use bash to read
#
f = `cat temp.txt`
puts f

Read entire file into memory and split the lines

f = File.read('temp.txt')
lines = f.split("\n")
lines.each do|line|
puts line
end

Read the file line by line instead of everything into memory

File.foreach('temp.txt') do|line|
puts line
end

File append without new line

f = File.open('temp.txt', 'a')
f.write(1)
f.write(2)
f.write(3)

File append with new line

f = File.open('temp.txt', 'a')
f.puts(4)
f.puts(5)
f.puts(6)

File write

f = File.open('temp.txt', 'w')
f.puts(7)
f.puts(8)
f.puts(9)

Random

puts rand()        # 0.7481252513698148
puts rand(9) # random number from 0 -> 8
puts rand(0..9) # random number from 0 -> 9

Try Catch

begin
do_something()
rescue => error
puts error
end

JSON

require 'json'
str = '{"name":"John", "age":30, "car":""}'
json = JSON.parse(str)
puts json['name'] # John
puts json['age'] # 30
puts json['dog'] #

< Back to all the stories I had written

--

--

Kevin FOO

A software engineer, a rock climbing, inline skating enthusiast, a husband, a father.