-1

I've recently picked up ruby and rails and have seen this :foo syntax in ruby with stuff like attr_accessor, in rails with model methods but I don't quite get it. What's the name of this syntax, what's it do ? an example of seen cases

class Dog
    attr_accessor :name
end

///second scenario
class CreatePurchases < ActiveRecord::Migration
def change
create_table :purchases do |t|
  t.string :name
  t.float :cost
  t.timestamps
  end
 end
end

//third scenario
class Purchase < ActiveRecord::Base
  validates :name, presence: true
  validates :cost, numericallity: {greater than : 0}
end
Eduardo Diaz
  • 49
  • 11

1 Answers1

1

The :foo syntax that you see around Ruby is called a Symbol, it is a type in the same way that a String is a type. In Ruby String are mutable objects, meaning they can be changed after being declared, symbols however can not. All the examples above that you have stated you could also use with Strings, like:

# with Strings
attr_accessor 'foo'
validates `name`

# with Symbols
attr_accessor :foo
validates :name

However in Ruby it is standard practice to use symbols, because of how they are allocated to memory and because they are faster in terms of performance. Strings are allocated a new space in memory everytime, even if they have the same content, because they are mutable. However as symbols are immutable, when you declare a symbol it stays in memory throughout a programs whole execution (meaning the garbage collector does not remove it) and also stored in a special 'dictionary', which is optimised for performance meaning that a symbol stays unique and can be very quickly retrieved.

John Hayes-Reed
  • 1,358
  • 7
  • 13