Why are exclamation marks used in Ruby methods?

后端 未结 10 2067
小蘑菇
小蘑菇 2020-11-22 06:01

In Ruby some methods have a question mark (?) that ask a question like include? that ask if the object in question is included, this then returns a

相关标签:
10条回答
  • 2020-11-22 06:21

    Bottom line: ! methods just change the value of the object they are called upon, whereas a method without ! returns a manipulated value without writing over the object the method was called upon.

    Only use ! if you do not plan on needing the original value stored at the variable you called the method on.

    I prefer to do something like:

    foo = "word"
    bar = foo.capitalize
    puts bar
    

    OR

    foo = "word"
    puts foo.capitalize
    

    Instead of

    foo = "word"
    foo.capitalize!
    puts foo
    

    Just in case I would like to access the original value again.

    0 讨论(0)
  • 2020-11-22 06:26

    Called "Destructive Methods" They tend to change the original copy of the object you are referring to.

    numbers=[1,0,10,5,8]
    numbers.collect{|n| puts n*2} # would multiply each number by two
    numbers #returns the same original copy
    numbers.collect!{|n| puts n*2} # would multiply each number by two and destructs the original copy from the array
    numbers   # returns [nil,nil,nil,nil,nil]
    
    0 讨论(0)
  • 2020-11-22 06:28

    This naming convention is lifted from Scheme.

    1.3.5 Naming conventions

    By convention, the names of procedures that always return a boolean value usually end in ``?''. Such procedures are called predicates.

    By convention, the names of procedures that store values into previously allocated locations (see section 3.4) usually end in ``!''. Such procedures are called mutation procedures. By convention, the value returned by a mutation procedure is unspecified.

    0 讨论(0)
  • 2020-11-22 06:31

    The exclamation point means many things, and sometimes you can't tell a lot from it other than "this is dangerous, be careful".

    As others have said, in standard methods it's often used to indicate a method that causes an object to mutate itself, but not always. Note that many standard methods change their receiver and don't have an exclamation point (pop, shift, clear), and some methods with exclamation points don't change their receiver (exit!). See this article for example.

    Other libraries may use it differently. In Rails an exclamation point often means that the method will throw an exception on failure rather than failing silently.

    It's a naming convention but many people use it in subtly different ways. In your own code a good rule of thumbs is to use it whenever a method is doing something "dangerous", especially when two methods with the same name exist and one of them is more "dangerous" than the other. "Dangerous" can mean nearly anything though.

    0 讨论(0)
提交回复
热议问题