legendary_rob
legendary_rob

Reputation: 13012

Ruby class level String management, variable vs method

I am seeing a lot of different preferences around the following:

class Foo
  VAR = "Some string".freeze

  # or 

  def self.var
    "Some String"
  end
end

both can be accessed the same way:

Foo::VAR 
#=> "Some String"

Foo::var
#=> "Some String"

but you can also do Foo.var to get the same string if it was a method. defining it as a variable feels like you break the power of encapsulation that OO gives us. I see however a lot of strings/magic numbers being stored in variables inside class's, this seems like a more common practice.

I am not sure which is right.

EDIT Sorry, my question is a little confusing. I wanted to find out if it's better to store strings in methods vs storing them in variables for a class. Me explaining how to call the methods confused the question.

Upvotes: 0

Views: 90

Answers (2)

RajG
RajG

Reputation: 832

Based on your question, storing immutable string in a CONSTANT makes more sense. Storing in a CONSTANT serves the basic purpose i.e. a constant which is available for all in your lexical scope(s).

Personally, storing "Some String" in a method is waste of resource as every-time self.var is called then we are initialising the receivers' again which in this scenario is not ideal. I say this as in Ruby Scope Gate plays a huge role and due to its dynamic nature and every-time you access a class and its methods you are entering a new scope. There is a similar question being asked here too.

Upvotes: 1

bixente.bvd
bixente.bvd

Reputation: 31

First, using a constant would guarantee that subclasses use not only the same string but also the same object.

  class Bar < Foo; end
  Foo::VAR.object_id == Bar::VAR.object_id # => true

And second, calling a class method with :: syntax is quite confusing, convention is to use . (see https://github.com/bbatsov/ruby-style-guide#double-colons)

So i would promote constant use

Upvotes: 0

Related Questions