Sometimes I see methods in Ruby that have "?" and "!" at the end of them, e.g:
name = "sample_string" name.reverse name.reverse! name.is_binary_data?
I was wondering what their purpose is? Are they just syntax sugarcoating?
By convention, method names begin with a lowercase letter. (Method names can begin with a capital letter, but that makes them look like constants.) When a method name is longer than one word, the usual convention is to separate the words with underscores like_this rather than using mixed case likeThis .
In Ruby, methods that end with exclamation marks typically modify the object they're called on. Ruby calls them dangerous methods, the exclamation mark in the method name could be considered a warning sign. This principle keeps method names shorter and makes the code easier to understand.
||= is called a conditional assignment operator. It basically works as = but with the exception that if a variable has already been assigned it will do nothing. First example: x ||= 10. Second example: x = 20 x ||= 10. In the first example x is now equal to 10.
It's "just sugarcoating" for readability, but they do have common meanings:
!
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.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.?
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?".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With