SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Guru Skyblaze's Avatar
    Join Date
    Jul 2005
    Location
    Italy
    Posts
    734
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    What does it means the "!" suffix in a method?

    I'm reading the sitepoint's rails book and i don't understand if the "!" suffix to method names is optional for all built-in methods (for example i use it whenever i want that method operates on the object directly in a destructive manner instead of operates on a copy of it) or it is optional only for methods that supports it.

  2. #2
    ☆★☆★ silver trophy vgarcia's Avatar
    Join Date
    Jan 2002
    Location
    in transition
    Posts
    21,235
    Mentioned
    1 Post(s)
    Tagged
    1 Thread(s)
    Only for methods that support it, not for all methods. For example, if you look at the documentation for the Array class, you'll see map() and map!(), but no sort!() method to go along with sort().

  3. #3
    SitePoint Guru Skyblaze's Avatar
    Join Date
    Jul 2005
    Location
    Italy
    Posts
    734
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ok as i imagined

  4. #4
    SitePoint Guru
    Join Date
    Aug 2005
    Posts
    986
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    There *is* a sort! method. I don't know why it isn't documented.

    There is no magic in the ! suffix: it's just an extra character allowed in Ruby method names. sort and sort! are two technically unrelated methods. They could be called sort and destructive_sort, but Ruby uses the ! *convention*. Many built in methods have a related destructive method.

    Code:
    class Array
      def sort
        ...
      end
    
      def sort!
        ...
      end
    end
    You can find these using:

    [].methods.grep /!/

    Which gives us all ! methods supported by Array:

    ["collect!", "compact!", "reject!", "slice!", "map!", "flatten!", "reverse!", "uniq!", "sort!"]


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •