Following the convention eases the readability of Ruby codes.
The question mark is for methods returning boolean values, like:
class Language attr_accessor :name def initialize(name) @name = name end def downcased? name == name.downcase end endand:
language = Language.new "ruby" language.downcased?returns:
=> true
Next. The exclamation mark in Ruby methods. In general, methods with trailing "!" indicate that the method will modify the object it's called on. The ones without are called "safe methods", and they return a copy of the orignal with changes applied to the copy, with the callee unchanged. For example:
original = "RUBY" copy = original.downcaseThe variable:
copycontains:
=> "ruby"while:
originalis still:
=> "RUBY"and please compare with trailing "!":
original = "RUBY" copy = original.downcase!The variable
copycontains:
=> "ruby"So a trailing "!" in a method name should mark that the object itself will be modified, when called. Syntactic sugar!
Supported by Ruby 1.9.3
Keine Kommentare:
Kommentar veröffentlichen