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

php - cannot display multiple markers in google maps v3 from traceroute result -

php - Boolean search on database with 5 million rows, very slow -

css - Text drops down with smaller window -