Reputation: 13
I have two classes in two seperate files. The script starts by executing file domain.rb
In the first file (domain.rb) I have the following code:
require 'message.rb'
class Domain
def create_domain
10.times do
puts "#{Message.site}"
end
end
In the second file (message.rb) I have this peace of code:
class Message
def self.site
@site = [*('a'..'z'),*('0'..'9')].shuffle[0,7].join
@site.concat("@example.com")
end
def other_method
puts "#{Message.site} later in the text #{Message.site}"
end
end
My Problem:
This way I'm executing the method .site three times ergo I'll receive 3 different outputs of shuffle method.
[email protected]
[email protected]
[email protected]
My Question: How can I ensure I can use [email protected] three times ?
Upvotes: 0
Views: 60
Reputation: 121000
Memoize the instance variable:
class Message
def self.site
@site ||= [*('a'..'z'),*('0'..'9')].
shuffle[0,7].
join.
concat("@example.com")
end
puts "#{Message.site} later in the text #{Message.site}"
end
Sidenote: Use Array#sample
with an argument instead of shuffling:
class Message
def self.site
@site ||= [*('a'..'z'),*('0'..'9')].
sample(8).
join.
concat("@example.com")
end
end
Upvotes: 2