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?