Skip to content

Instantly share code, notes, and snippets.

@johansenja
Last active March 17, 2021 10:33
Show Gist options
  • Save johansenja/2545e24691a6eaf374b64d1284ce5b7b to your computer and use it in GitHub Desktop.
Save johansenja/2545e24691a6eaf374b64d1284ce5b7b to your computer and use it in GitHub Desktop.
Enough Ruby to get started with Rails
#### Basic data types you need to know ####
nil
"String"
:Symbol # immutable; often used as identifiers for methods or properties, esp. as keys of hashes
1.is_a? Integer # true
1.0.is_a? Float # true
# Arrays:
my_array = []
my_array2 = Array.new
# Hash:
my_hash = {}
my_hash2 = Hash.new
my_hash3 = { hello: 'world' } # also sometimes seen as { :hello => 'world' }
# or with string keys: { 'hello' => 'world }
# it is super easy to compare arrays and hashes, even if they are fully of complex objects (or nested)
my_array == my_array2 # true
my_hash == my_hash2 # true
# Reading from both arrays and hashes is done with '[]'; '.' is reserved for method calls
my_array << 'hi'
my_array[0] # 'hi'
my_hash[:hello] = 'world'
my_hash[:hello] # 'world'
my_hash.length # 1
my_hash.hello # undefined method 'hello' for Hash
my_hash4 = { { hash_as_key: true} => 10 } # anything can be the key of a hash - even another hash
my_hash4[{ hash_as_key: true }] # 10
#### classes ####
# super easy to define a class
class MyClass
end
# or a class with inheritance
class SpecialString < String
end
# methods are public by default, but can also be protected or private. Anything defined below a `protected` or `private`
# will still be protected/private
class MyString < String
def public_by_default
1
end
protected
def protected_method1
'hello'
end
def protected_method2
end
private
def private_method1
'I am private'
end
def private_method2
'I am also private'
end
end
#### Loops ####
# Ruby tends to use iterators rather than explicit `for` loops.
# It has a very rich standard library with more or less something for everything
my_arr = [1,2,3,4,5,6]
# log each item in an array
my_arr.each do |number|
p number
end
sum_by_doubles = my_arr.sum do |number|
number * 2
end
evens = my_arr.filter do |number|
number % 2 == 0
end
### Other useful things to remember ###
# methods always have an implicit return
def number
1
end
number # returns 1
# methods don't need parentheses to be called. This is helpful with chaining
def nested_arr
[ ['hello'] ]
end
nested_arr.first.first.length > 0
# parentheses are optional for passing arguments
def m1(a, b, c, d)
end
m1 0, 1, 2, 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment