My Ruby Cheat Sheet

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
s='hello world'
puts s.index('z') #
puts s.include? 'z' # false
puts s.index('o') # 4
puts s.include? 'o' # true
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
%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"
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
f = File.read('temp.txt')
lines = f.split("\n")
lines.each do|line|
puts line
end
File.foreach('temp.txt') do|line|
puts line
end
f = File.open('temp.txt', 'a')
f.write(1)
f.write(2)
f.write(3)
f = File.open('temp.txt', 'a')
f.puts(4)
f.puts(5)
f.puts(6)
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'] #

--

--

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
Kevin FOO

Kevin FOO

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