From: "David A. Black" Date: 2009-09-22T11:23:31+09:00 Subject: Re: start_with Hi -- On Tue, 22 Sep 2009, Rong wrote: > Can someone explain why this doesn't work? > > class Person > attr_accessor :firstName > > P=[] > def initialize > P << self > end > def self.find_person(part) > P.each {|e| if e.firstName.start_with(part) then return e end} You mean start_with? (with question mark). Also, you've got a bug. The #each method returns its receiver. That means that if nothing triggers the return inside the block, you'll get back the whole P array. See below.... > end > end > > u=Person.new > u.firstName="Ron" > r=Person.new > r.firstName="Bob" > > q=Person.find_person("Ro") > puts q.firstName p Person.find_person("nobody") Output: [#, #] What you want is: def self.find_person(part) P.find {|e| e.firstName.start_with(part) } end which will return nil if nothing is found. (Also, first_name would be more idiomatic than firstName, as a variable name.) I've got reservations about using a constant as a modifiable array like you're doing, but one (or two) thing(s) at a time :-) David -- David A. Black, Director Ruby Power and Light, LLC (http://www.rubypal.com) Ruby/Rails training, consulting, mentoring, code review Book: The Well-Grounded Rubyist (http://www.manning.com/black2)