In python there is a pass
keyword for defining an empty function, condition, loop, ... Is there something similar for Ruby?
Python Example:
def some_function(): # do nothing pass
Ruby is pass-by-value, but the values it passes are references. A function receives a reference to (and will access) the same object in memory as used by the caller.
So when you are calling a method in Ruby, the parameters are copied by value from the source variables but they are ultimately references to slots. We can show it this way. You can see that the parameter inside the method call also contains the same object_id as the outside variable that was passed to it.
||= is called a conditional assignment operator. It basically works as = but with the exception that if a variable has already been assigned it will do nothing. First example: x ||= 10. Second example: x = 20 x ||= 10. In the first example x is now equal to 10.
In `ruby`, the body of an object is expressed by a struct and always handled via a pointer. A different struct type is used for each class, but the pointer type will always be `VALUE` (figure 1). In practice, when using a `VALUE`, we cast it to the pointer to each object struct.
No, there is no such thing in Ruby. If you want an empty block, method, module, class etc., just write an empty block:
def some_method end
That's it.
In Python, every block is required to contain at least one statement, that's why you need a "fake" no-op statement. Ruby doesn't have statements, it only has expressions, and it is perfectly legal for a block to contain zero expressions.
nil
is probably the equivalent of it:
def some_function nil end
It's basically helpful when ignoring exceptions using a simple one-line statement:
Process.kill('CONT', pid) rescue nil
Instead of using a block:
begin Process.kill('CONT') rescue end
And dropping nil
would cause syntax error:
> throw :x rescue SyntaxError: (irb):19: syntax error, unexpected end-of-input from /usr/bin/irb:11:in `<main>'
Notes:
def some_function; end; some_function
returns nil
.
def a; :b; begin; throw :x; rescue; end; end; a;
also returns nil
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With