Dot
The .
(dot) symbol shows up in a couple different ways in Ruby. We use it to indicate the receiver of a method call. We also use it to declare some numeric values like float literals.
Not what you're looking for? Maybe you're looking for multiple dots like are used in Range Literals or in the Flip Flop operator.
Method Calls
Ruby is heavily inspired by Smalltalk which was built on the idea of message passing. The idea is that to call a method is to send a message to the object (instance) that knows what that message means and what to do with it. The message is the method name and arguments. The object receiving the message is the receiver.
With that history lesson in mind, we use the .
to indicate who the reciever of the message should be.
> 1.+(2)
=> 3
> "hello, world!".upcase
=> "HELLO, WORLD!"
> [1,2,3].<< 4
=> [1, 2, 3, 4]
> square = ->(x) { x * x }
=> #<Proc:0x00007fdb4498f4f0 (irb):396 (lambda)>
> square.call(3)
=> 9
We wouldn't necessarily call all of these methods this way, but it is good to remember that even things like +
and <<
are methods in their own right.
We don't always need to indicate a receiver if it can be implied in the present context.
class Greeting
def self.hello
"Hello"
end
def initialize(who)
@who = who
end
def hello
msg = "#{Greeting.hello}, #{@who}"
emphasize(msg)
end
private
def emphasize(str)
"#{str}!"
end
end
puts Greeting.hello
puts Greeting.new("Ruby").hello
Notice in this example that emphasize
can be called in the context of another instance method without indicating that the receiver is self
. To reference the class method ::hello
from an instance method context, we do need to indicate Greeting.hello
. Otherwise, the instance method #hello
itself would be called in an infinite loop.
And here is a bit of a method-calling oddity: a method can be called with ::
instead of .
. Though we and the Ruby Docs recommend not doing this since it would be easy to confuse it with Module Namespacing.
> 'html'::upcase
=> "HTML"
Number Literals
Number types like Floats and Rationals use a .
in their declaration.
> 12.34
=> 12.34
> 0.876
=> 0.876
> 12.34r
=> (617/50)
> 12.34ri
=> (0+(617/50)*i)