sempsteen
11/25/2006 9:24:00 AM
Hi all,
First of all sorry for my english.
I'm a Ruby newbie, trying to learn the language from the book, "The
Pragmatic Programmer's Guide". I loved the language very much. Now i
have some question marks about some issues.
If you help me understand this concept i'll be very happy.
1-) What does "Hash#has_key?" actually do?
Why do we need such a method in spite of using the result of "Hash#[]"
method which will return nil for a non-present key.
2-) If we go ahead by the same manner is this a correct way of writing
a program that finds amicable numbers:
class Fixnum
def has_friend?
t1, t2 = 0, 0
1.upto(self / 2) {|i| t1 += i if self % i == 0}
1.upto(t1 / 2) {|i| t2 += i if t1 % i == 0}
if self == t2 and self != t1
return true
else
return false
end
end
def friend
t1, t2 = 0, 0
1.upto(self / 2) {|i| t1 += i if self % i == 0}
1.upto(t1 / 2) {|i| t2 += i if t1 % i == 0}
return t1 if self == t2 and self != t1
end
end
1.upto(1000) {|i| print i, "\t<=>\t", i.friend, "\n" if i.has_friend?}