Eighth article in the Prepare for a Ruby job interview series. In this article, we will go over some random Ruby tricks and information.
The 4 ways to call a method
object = Object.new object.object_id
Symbol vs String
Symbols are unique immutable entities as opposed to string which are mutable.
:fu.object_id # 522248 :fu.object_id # 522248 'fu'.object_id # 70139185894080 'fu'.object_id # 70139182497200
As you can see, the
:fu symbol is always the same but the
'fu' string changes. Symbols are more memory efficient so don’t hesitate to use them
I don’t recommend using global variables but you should be able to recognize them. Actually, you just have to add dollar sign, it will remind you of PHP yay !
$fu = 'fu' # That's a global variable. But don't do it.
What is Self
Self gives you the current object, be it a class, or anything else.
The ||= operator
This operator is super useful to initialize variable when they might already hold data.
a ||= b
is the equivalent of :
a || a = b
If you define a method at the top level scope, it goes to Object
def yo p 'yo' end Object.yo # => 'yo'
One liner method declaration
def greet; puts "hello"; end def hello() :hello end
Checkout the next article about the FizzBuzz and Fibonacci algorithms.