Ruby Flashcards
Add a list of elements to an array, return the array
[1, 2] + [1, 2]
=> [1, 2, 1, 2]
Class instance variables (visible from class methods)?
class Dog @type = 'awesome' # OR... class \<\< self; attr\_reader :type; end;
def self.type
@type
end
end
Range from n to 0, inclusive
n.downto(0) OR n.step(0, -1)
Repeat value ‘a’ n times
[‘a’] * 5
Initialize a hash that defaults a missing value to 0
Hash.new(0) # h[:a] does not modify
Hash.new { |h, k| h[k] = 0 } # h[:a] modifies
Head/first, rest, initial, last?
first, *rest = arr
*initial, tail = arr
Falsey values?
false nil
Cast to int
‘13a’.to_i
=> 13
Inspect instance methods, exclude inherited
Integer.instance_methods(false)
Inspect instance methods, include inherited
Integer.instance_methods
Switch statement
case obj
when 1..5 then x
when Float then y
when /(regex)/ then $1
else ‘z’
# Under the hood: /(regex)/ === obj
end
Read lines of file
File.readlines(files)
Trim whitespace from both sides of a string
” a “.strip
Trim X from end of string
‘xxabcxx’.sub(/x+$/, ‘’)
=> ‘xxabc’
Detect if beginning/end of string matches
‘abc’.end_with?(‘c’) // start_with?
Create a RegExp with interpolation
/#{str}/im # ignore case, multiline
Detect if string matches a RegExp
/\w\s(\w+)/ =~ ‘Jason Benn’
=> int or nil
Grab nth match group from string
“Jason Benn”[/\w+\s(\w+)/, 1]
=> “Benn”
Sort a map by a criteria
map.sort_by { |k, v| v }.to_h # many enumerable methods return arrays
Filter a map by a criteria
map.select { |k, v| v }
Connect to a database
db = PG.connect(con_string)
Slice iterable from 2 til the end
[1, 2, 3, 4].slice(2..-1)
=> [3, 4]
Test if all/any of a collection’s element pass a truth test
all?/any?
Initialize a date to a date object
require ‘date’
DateTime.parse(‘…’)
Display a date in a particular format
d.strftime(‘%H:%M, %h %d %Y’)