Showing posts with label Comparable. Show all posts
Showing posts with label Comparable. Show all posts

Sunday, March 08, 2009

String compare trap in php

If string compare with an integer, php will evaluate string to integer intval() and compare it with that integer.

if('test' != 0) {
echo "true";
} else {
echo "false"; // return false
}
if('0test' != 0) {
echo "true";
} else {
echo "false"; // return false
}
if('1test' != 0) {
echo "true"; // return true
} else {
echo "false";
}

Thursday, June 28, 2007

Ruby's module mixin

# All you have to do is write an iterator called each, which returns the elements of our collection in turn. Mix in Enumerable, and suddenly your class supports things such as map, include?, and find_all?. If the objects in your collection implement meaningful ordering semantics using the <=> method, you’ll also get methods such as min, max, and sort.


class A
include Comparable
include Enumerable
attr :n

def initialize(n)
@n = n
end

def each
(1..@n).each do |i|
yield i
end
end

def <=>(b)
self.n <=> b.n
end
end

a = A.new(3)
b = A.new(4)

m = a.map {|i| i.to_s + __LINE__.to_s}

p m

n = a > b

p n