我创建了一个类,该类将在创建类的实例时使用 faker gem 自动填充数据。我无法让 Person 对象填充。这可能是一个笨拙的语法错误。
require 'rubygems'
require 'faker'
class Person
attr_accessor :firstname , :lastname, :phonenumber, :workaddress, :bio, :email
def initialize(firstname = Faker::Name.first_name ,
lastname = Faker::Name.last_name,
phonenumber = Faker::PhoneNumber.phone_number,
workaddress = "#{Faker::Address.street_name},
#{Faker::Address.city}, #{Faker::Address.state_abbr}, #{Faker::Address.zip}",
bio = 'bla bla bla',
email = Faker::Internet.email)
end
end
我在 ruby 解释器中运行了上面的代码,但我无法初始化 Class 属性,以下产生 nillClass 而不是 String。
p = Person.new
puts p.firstname.class
工作解决方案:
def initialize(firstname = Faker::Name.first_name ,lastname =Faker::Name.last_name,phonenumber = Faker::PhoneNumber.phone_number,workaddress = "# {Faker::Address.street_name}, #{Faker::Address.city}, #{Faker::Address.state_abbr}, #{Faker::Address.zip}",bio = "#{Lolem.new.words(7)}", email = Faker::Internet.email)
@firstname = firstname
@lastname = lastname
@phonenumber = phonenumber
@workaddress = workaddress
@bio = bio
@email = email
end