I’m still learning Ruby, and I’m curious about whether it is appropriate to use a class variable, constant, or local variable in this scenario.
In my below code example (that generates random usernames out of a fixed character set), assigning @username
as an instance variable is fairly obvious. But I’m curious whether I should assign the charset as a constant or maybe a class variable. What would be the advantages of using another variable type in this scenario?
In the current example, the _charset
is computed in every instance. (Do correct me if my assumption is wrong.) I also assume the computation would be shared between instances (as opposed to recomputed) as both a class variable and as a constant?
class NewAccount
def initialize
@username = self.generate_username
end
def generate_username
_charset = ( a .. z ).to_a + ( 0 .. 9 ).to_a
_newusername = Array.new(20) { _charset[rand(_charset.length)] }.join
return _newusername
end
end