Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of “pass” in Ruby

Tags:

ruby

keyword

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 
like image 224
user1251007 Avatar asked Nov 19 '12 11:11

user1251007


People also ask

Is Ruby pass by value?

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.

How are parameters passed in Ruby?

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.

What is ||= in Ruby?

||= 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.

Does Ruby have pointers?

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.


2 Answers

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.

like image 124
Jörg W Mittag Avatar answered Oct 02 '22 17:10

Jörg W Mittag


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.

like image 20
konsolebox Avatar answered Oct 02 '22 17:10

konsolebox