ruby - Checking Variables In The Constructor -


i learning ruby , know in other languages can ensure variables not empty when initializing.

how in ruby example?

class person   attr_reader :name    def initialize name      @name = name   end end 

without setting default name, , raising exception if empty string sent (not nil) argument, raise exception.

class person   attr_reader :name    def initialize name      raise "name can not empty string" if name.empty?     @name = name   end end 

then if send empty string error similar this:

temp.rb:5:in `initialize': name can not empty string (runtimeerror)

 temp.rb:11:in `new'  temp.rb:11:in `<main>' 

shell returned 1

as far part of "it makes them enter name until valid" mentioned in comment... should let running code this.

this allowing no default, forcing user use other empty string.

class personnameerror < exception end class person   attr_reader :name    def initialize name     @name = name   end end  begin   print "what name? "   name = gets.chomp   raise personnameerror if name.empty?   person = person.new(name) rescue personnameerror   if name.empty?     puts "you can not have name ''"     retry   else     raise   end end  puts person.name 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -