Anki cards for Ruby
Flashcards for Ruby. Created with Obsidian Anki Sync notation.
[TOC]
default value if variable is nil
::
# number MUST be nil!
# Doesn't work if it's an undefined var.
var = number || 5
default value if argument is not passed
::
def method(parameter = "default value")
# ...
end
declare a Class method to be called from the Class name
::
use self.method_name
:
class Hello
def self.world
"Hello World!"
end
end
autocreate getters/setters
::
use attr_accessor
:
class Person
attr_accessor :first_name, :last_name
end
what does String.count
do?
::
counts how many "char-set" there are in the string
>> 'meleu'.count('e')
=> 2
>> 'meleu'.count('el')
=> 3
how Array.map
works?::
returns a new array with the results of running a block once for every element in the array (enumeration)
# raise all numbers to square
>> [1, 2, 3].map { |num| num ** 2 }
=> [1, 4, 9]
get an array with no repeated items
::
# use .uniq method
>> [1, 2, 3, 4, 5, 2, 2, 4, 5].uniq
=> [1, 2, 3, 4, 5]
String.scan
vs. String.split
?
::
.scan
searches for the items.split
searches for the separators
>> "item1--item2--itemN".split("--")
=> ["item1", "item2", "itemN"]
>> "item1--item2--itemN".split("-")
=> ["item1", "", "item2", "", "itemN"]
>> "item1--item2-:itemN".scan(/item./)
=> ["item1", "item2", "itemN"]
from char to ASCII value
::
'a'.ord # ordinal
# => 97
from ASCII value to char
::
97.chr
# => "a"
subtract arrays
::
[1, 2, 3] - [1, 3]
# => [2]
create an Array
from a Range
::
# n00b way
alphabet = ('a'..'z').to_a
# ninja way
alphabet = [*'a'..'z']
capture an Exception
::
begin
# ... code that can raise an exception...
rescue ExceptionName => e
# ... code to run when getting an exception
end
How do you clean an Array
from items matching a condition?
::
Using #reject
iterator (think of a negation of #select
)
a = [1, 2, 3, 4]
# reject the even numbers:
a.reject { |n| n.even? }
# => [1, 3]
How would you sort an Array
with a given sorting criteria?
::
Defining the criteria in a block to #sort_by
strings_array.sort_by do |word|
word.length
end