What Does the Question Mark At the End of a Method Name Mean in Ruby

What does the question mark at the end of a method name mean in Ruby?

It is a code style convention; it indicates that a method returns a boolean value (true or false) or an object to indicate a true value (or “truthy” value).

The question mark is a valid character at the end of a method name.

https://docs.ruby-lang.org/en/2.0.0/syntax/methods_rdoc.html#label-Method+Names

What is the purpose of ! and ? at the end of method names?

It's "just sugarcoating" for readability, but they do have common meanings:

  • Methods ending in ! perform some permanent or potentially dangerous change; for example:
    • Enumerable#sort returns a sorted version of the object while Enumerable#sort! sorts it in place.
    • In Rails, ActiveRecord::Base#save returns false if saving failed, while ActiveRecord::Base#save! raises an exception.
    • Kernel::exit causes a script to exit, while Kernel::exit! does so immediately, bypassing any exit handlers.
  • Methods ending in ? return a boolean, which makes the code flow even more intuitively like a sentence — if number.zero? reads like "if the number is zero", but if number.zero just looks weird.

In your example, name.reverse evaluates to a reversed string, but only after the name.reverse! line does the name variable actually contain the reversed name. name.is_binary_data? looks like "is name binary data?".

Should a method ending in ? (question mark) return only a boolean?

A method ending with ? should return a value which can be evaluated to true or false. If you want to ensure a boolean return, you can do so by adding a double bang to the finder.

def is_subscribed?(feed_url)
!!Subscription.find_by_user_id_and_feed_id(self[ :id ], Feed.find_by_feed_url(feed_url))
end

Ruby question mark operator, what does this mean?

  1. (true ? rand(13) : 0) mean (if true then rand(13) else 0 end)

if you have directly "true" in condition, the "else" is never called (is useless), you can write : a = 1 + rand(13) directly ;)


  1. rand(13) give random int between 0 and 12 ;)
    if you want "13" put rand(14)
    personally I always use range like this (all range is include, it's easier to understand) : rand(0..13)

In Rails' ActiveRecord, what does a question mark at the end of a method name corresponding to a column do?

It will return true if a field is present? or not. So an empty string "" will return false.

Using a question mark in ruby methods

Note that if you comment out the line causing your error (@attacked? = false), you will still get an error relating to the question mark:

NameError: invalid attribute name `attacked?'

The problem is that ? is not a valid character in a variable name. The first error (the SyntaxError that you’re seeing) is caused at parse time and caught immediately. The second error is caused when Ruby tries to evaluate the code and cannot create an instance variable with a name containing an invalid character.

A question mark is a valid character at the end of a method name though (actually it’s possible to have a method with a ? anywhere in its name, but you can’t call such a method directly).

One way to achieve what you want is something like this:

class Player
attr_accessor :name, :health, :attacked
alias :attacked? :attacked

def initialize(name)
@name = name
@health = 100
@attacked = false
end
end

This leaves attacked without the question mark, but adds attacked? as an alias.

What does ! mean at the end of a Ruby method definition?

Ruby doesn't treat the ! as a special character at the end of a method name. By convention, methods ending in ! have some sort of side-effect or other issue that the method author is trying to draw attention to. Examples are methods that do in-place changes, or might throw an exception, or proceed with an action despite warnings.

For example, here's how String#upcase! compares to String#upcase:

1.9.3p392 :004 > foo = "whatever"
=> "whatever"
1.9.3p392 :005 > foo.upcase
=> "WHATEVER"
1.9.3p392 :006 > foo
=> "whatever"
1.9.3p392 :007 > foo.upcase!
=> "WHATEVER"
1.9.3p392 :008 > foo
=> "WHATEVER"

ActiveRecord makes extensive use of bang-methods for things like save!, which raises an exception on failure (vs save, which returns true/false but doesn't raise an exception).

It's a "heads up!" flag, but there's nothing that enforces this. You could end all your methods in !, if you wanted to confuse and/or scare people.

Why are exclamation marks used in Ruby methods?

In general, methods that end in ! indicate that the method will modify the object it's called on. Ruby calls these as "dangerous methods" because they change state that someone else might have a reference to. Here's a simple example for strings:

foo = "A STRING"  # a string called foo
foo.downcase! # modifies foo itself
puts foo # prints modified foo

This will output:

a string

In the standard libraries, there are a lot of places you'll see pairs of similarly named methods, one with the ! and one without. The ones without are called "safe methods", and they return a copy of the original with changes applied to the copy, with the callee unchanged. Here's the same example without the !:

foo = "A STRING"    # a string called foo
bar = foo.downcase # doesn't modify foo; returns a modified string
puts foo # prints unchanged foo
puts bar # prints newly created bar

This outputs:

A STRING
a string

Keep in mind this is just a convention, but a lot of Ruby classes follow it. It also helps you keep track of what's getting modified in your code.

what does ? ? mean in ruby

Functions that end with ? in Ruby are functions that only return a boolean, that is, true, or false.

When you write a function that can only return true or false, you should end the function name with a question mark.

The example you gave shows a ternary statement, which is a one-line if-statement. .nil? is a boolean function that returns true if the value is nil and false if it is not. It first checks if the function is true, or false. Then performs an if/else to assign the value (if the .nil? function returns true, it gets nil as value, else it gets the File.join(root_dir, '/') as value.

It can be rewritten like so:

if root_dir.nil?
prefix = nil
else
prefix = File.join(root_dir, '/')
end


Related Topics



Leave a reply



Submit