26

What are the various meanings of the Ruby sharp/number sign/pound/hash(#) symbol

How many contexts does the symbol # in Ruby have ?

I know that #` represents comment

# a comment

or 'convert to the value':

i = 1
print "#{i}" # simple example

However I also see some Ruby docs describe built-in methods like these:

Array#fill
File::file?

Why do they describe the same thing using 2 different symbols ? I am new in Ruby. Thanks

unom
  • 11,438
  • 4
  • 34
  • 54
JACK M
  • 2,627
  • 3
  • 25
  • 43

4 Answers4

16

This is how instance method described:

Array#fill 

So you can:

a = Array.new(2)
 => [nil, nil]
a.fill(42)
 => [42, 42]

This is how class method described:

String::new

s = String.new('abc')
 => "abc"
freemanoid
  • 14,592
  • 6
  • 54
  • 77
11

In Perl, # is used for commenting, and since Perl is an 'ancestor' of Ruby, the role was carried over.

The "#{}" syntax is called 'interpolation' and the pound was picked most likely because interpolation is similar in a sense to commenting, because you are changing the context of your code (in this case to another context for execution)

The # following a Class name is just meant to indicate the following identifier is a method of that Class, and is just a convention. Read more about it here: Why are methods in Ruby documentation preceded by a hash sign?

Community
  • 1
  • 1
Steve Benner
  • 1,679
  • 22
  • 26
2

The :: is interesting, it acts similarly to the . in that you can call methods via both

Car::is_hybrid?

and

car.is_hybrid?

As you will see in most code though . is preferred for methods.

One case where :: is often preferred is where you have constant in the class and you will see this in system calls such as Math::PI or ones you create, e.g. ThePentagon::NUMBER_OF_BUILDING_SIDES

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
1

Just to show you as an example,that Ruby shows instance method preceded with the symbol # and class methods preceded with the symbol ..

class Foo
  def self.foo;end
  def bar;end
end

p Foo.method(:foo) # => #<Method: Foo.foo>
p Foo.new.method(:bar) # => #<Method: Foo#bar>
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317