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
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
No, there is no such thing in Ruby. If you want an empty block, method, module, class etc., just write an empty block:
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.
Single line functions and classes
works fine for pseudocode.
As answered before everything in ruby is an expression so it is fine to leave it blank.
A ruby alternative for python programmers who love the pass keyword
Note that it is useless to do this in Ruby since it allows empty methods but if you're that keen on
pass
, this is the simplest and cleanest alternative.and now you can use this function inside any block and it will work the same.
Keep in mind that pass is a function that returns, so it is up to you how you can use it.
nil
is probably the equivalent of it:It's basically helpful when ignoring exceptions using a simple one-line statement:
Instead of using a block:
And dropping
nil
would cause syntax error:Notes:
def some_function; end; some_function
returnsnil
.def a; :b; begin; throw :x; rescue; end; end; a;
also returnsnil
.If you want to be able to use it freely with any number of arguments, you have to have a small trick on the arguments:
As others have said, in Ruby you can just leave a method body empty. However, this could prove a bit different than what Python accomplishes with
pass
.In Ruby, everything is an object. The absence of value, which some programming languages indicate with
null
ornil
is actually an object ofNilClass
in Ruby.Consider the following example (in
irb
):Here's Ruby's NilClass documentation for reference.
I believe Python's
pass
is used mainly to overcome the syntactic limitations of the language (indentation), although I'm not that experienced in Python.You always have
end
statements, sopass
is not needed.Ruby example: