Ruby Flashcards

1
Q

Add a list of elements to an array, return the array

A

[1, 2] + [1, 2]
=> [1, 2, 1, 2]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Class instance variables (visible from class methods)?

A
class Dog
 @type = 'awesome' # OR...
 class \<\< self; attr\_reader :type; end;

def self.type
@type
end
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Range from n to 0, inclusive

A

n.downto(0) OR n.step(0, -1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Repeat value ‘a’ n times

A

[‘a’] * 5

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Initialize a hash that defaults a missing value to 0

A

Hash.new(0) # h[:a] does not modify
Hash.new { |h, k| h[k] = 0 } # h[:a] modifies

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Head/first, rest, initial, last?

A

first, *rest = arr

*initial, tail = arr

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Falsey values?

A

false nil

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Cast to int

A

‘13a’.to_i

=> 13

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Inspect instance methods, exclude inherited

A

Integer.instance_methods(false)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Inspect instance methods, include inherited

A

Integer.instance_methods

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Switch statement

A

case obj
when 1..5 then x
when Float then y
when /(regex)/ then $1
else ‘z’
# Under the hood: /(regex)/ === obj
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Read lines of file

A

File.readlines(files)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Trim whitespace from both sides of a string

A

” a “.strip

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Trim X from end of string

A

‘xxabcxx’.sub(/x+$/, ‘’)
=> ‘xxabc’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Detect if beginning/end of string matches

A

‘abc’.end_with?(‘c’) // start_with?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Create a RegExp with interpolation

A

/#{str}/im # ignore case, multiline

17
Q

Detect if string matches a RegExp

A

/\w\s(\w+)/ =~ ‘Jason Benn’

=> int or nil

18
Q

Grab nth match group from string

A

“Jason Benn”[/\w+\s(\w+)/, 1]
=> “Benn”

19
Q

Sort a map by a criteria

A

map.sort_by { |k, v| v }.to_h # many enumerable methods return arrays

20
Q

Filter a map by a criteria

A

map.select { |k, v| v }

21
Q

Connect to a database

A

db = PG.connect(con_string)

22
Q

Slice iterable from 2 til the end

A

[1, 2, 3, 4].slice(2..-1)

=> [3, 4]

23
Q

Test if all/any of a collection’s element pass a truth test

A

all?/any?

24
Q

Initialize a date to a date object

A

require ‘date’

DateTime.parse(‘…’)

25
Q

Display a date in a particular format

A

d.strftime(‘%H:%M, %h %d %Y’)

26
Q
A