1.times
"hello".split
[].size
{}.merge({})
true.klass
def hello(some_arg)
return 5
end
def hi(some_arg)
5
end
>>> hello "arg"
5
>>> hi "arg"
5
>>> hi hello "arg" # NONONONONONOO
>>> hi(hello("arg")) # YES
camelCase = 2 # NO NONONONO
snake_case = 5 # Yes
class CamelCase # YES
...
class snake_case # NONONONO
...
foo = 5
baz = []
bar = {}
a = true
b = "hello"
a = "hello"
b = "world"
c = "#{a} #{b}"
>>> puts c
"hello world"
Interpolation
a = "hello "
a << "world"
>>> puts a
"hello world"
Substrings
a = "hello world"
>>> a[1..2]
"el"
>>> a[1...2]
"e"
Everything is true....
...except nil and false
>>> puts true if "hello"
true
>>> puts true if 0
true
>>> puts "nope" if nil
>>> puts "nope" unless false
"nope"
a = [1,2,3]
>>> a.first
1
>>> a.last
3
>> a[0]
1
>>> Array.new(3, 0)
[0,0,0]
We'll come back to arrays in a bit!
Python dictionaries
{
:a => 1,
:b => 2,
}
{
a: 1,
b: 2,
}
{
"a" => 1,
"b" => 2,
}
Kind of like strings, but not really.
(they don't have string methods)
>>> :hello = 5
SyntaxError: syntax error, unexpected '=', expecting end-of-input
Can't be mutated
a = :"helloworld"
>>> puts a
helloworld
>> a
:helloworld
>>> :helloworld == "helloworld"
false
class MyClass < ParentClass
def self.class_method
puts "this is a class method"
end
def instance_method(arg="default")
puts arg
end
private
def snake_case
end
protected
def baz
end
end
>>> MyClass.class_method
"this is a class method"
>>> instance = MyClass.new
>>> instance.instance_method "hello"
"hello"
>>> instance = MyClass.new
>>> instance.instance_method
"default"
if true
1
elsif a == 5
2
else
3
end
list = ['a', 'b', 'c']
for element in list:
print(element)
['a', 'b', 'c'].each { |element| puts element }
['a', 'b', 'c'].each do |element|
puts element
end
Python
Ruby
Similar to lambda expressions in Python
lambda x: x % 3 == 0
{ |element| puts element }
lambda x: print(x)
Equals
Other useful blocks
>>> [1,2,3].map { |n| n * 2 }
[2, 4, 6]
>>> 3.times { puts 5 }
5
5
5
>>> [1,2,3].select { |n| n % 2 == 0 }
[2]
>> [1,2,3].any? { |n| n % 2 == 0 }
true
>>> [1,2,3].max_by { |n| n }
3
See the Ruby Enumerable documentation for more!
Thanks for coming!