PJCHENder
PJCHENder

Reputation: 6010

How and why does a method's name become a symbol in Ruby?

I am wondering why and how a method's name become a symbol in Ruby automatically. When I run the code below:

# create a BankAccount class
class BankAccount
  def initialize(name)
    @name = name
    @transactions = []
  end

  def get_name
    @name
  end
end

aaron = BankAccount.new("Aaron")
aaron.methods

It will automatically create an ":get_name" symbol, what does this refers to? and how does this happens?


What I mean is that in JavaScript, I can define a name of method by:

let fn = function(){
  return "This is a function"
}

console.log(fn)

Through console.log(fn), I can get the "fn". But in Ruby, if that fn will become :fn? or what the difference of "fn" and ":fn"?

Sorry for unclear description?


I check the documentation.

Does the name of the function become an symbol while defining the method by the Method#name ??

Upvotes: 3

Views: 1638

Answers (2)

akuhn
akuhn

Reputation: 27793

Great question.

Your observation is correct.

Method names are internally stored as symbols. Each Ruby class has an internal hash, that maps symbols to an instruction sequence of bytecode. Whereas Javascript either does not distinguish between strings and symbols or does not expose this distinction to the programmer, the latter is more likely.

Symbols are a concept that goes back to early languages like Smalltalk and Scheme. They are internal representations of a string with the additional contract that all symbols with the same name are always the same object. This allows the language to optimize internal processes like calling a method or looking up a class name.

Fun fact, Ruby symbols are represented as tagged integers internally and there is an internal table that maps these magic numbers to identifier names.

Upvotes: 4

tadman
tadman

Reputation: 211560

A method name doesn't "automatically" become anything. The methods method simply returns what methods have been defined and describes them as symbols, nothing more.

If you want to do some research into a method specifically, do this:

aaron.method(:get_name)
# => #<Method: BankAccount#get_name>

Note that this is exactly equivalent:

aaron.method("get_name")

The method method does not care if you give it a string or symbol, it converts as necessary.

Then you can interrogate that with things like:

aaron.method(:get_name).source_location

Anything else the Method class supports is likewise valid.

Upvotes: 1

Related Questions