Equivalent of “pass” in Ruby

2019-03-22 10:38发布

问题:

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

回答1:

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.



回答2:

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.



回答3:

You always have end statements, so pass is not needed.

Ruby example:

def some_function()
    # do nothing
end


回答4:

Single line functions and classes

def name ; end

class Name ; end

works fine for pseudocode.

As answered before everything in ruby is an expression so it is fine to leave it blank.

def name
end

class Name
end

A ruby alternative for python programmers who love the pass keyword

def pass
end

# OR

def pass; end

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.

def name
   pass
end

# OR

class Name
   pass
end

Keep in mind that pass is a function that returns, so it is up to you how you can use it.



回答5:

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:

def gobble *args, &pr; end


回答6:

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 or nil is actually an object of NilClass in Ruby.

Consider the following example (in irb):

class A
  def no_op
  end
end

A.new.no_op
# => nil
A.new.no_op.class
# => NilClass
A.new.no_op.nil?
# => true

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.



标签: ruby keyword