Use LEFT and RIGHT arrow keys to navigate between flashcards;
Use UP and DOWN arrow keys to flip the card;
H to show hint;
A reads text to speech;
3 Cards in this Set
- Front
- Back
Objects in Ruby
|
Every class in Ruby is a subclass of Object, everything is an instance of Object.
In Ruby, everything is an Object. That means that hashes, strings, objects from user-defined classes, and even numbers and strings all have methods. |
|
Equality in Ruby
|
Object defines a method == that compares two objects and returns true if they are equal. Two objects are equal if they have the same value; this works for all built in Ruby classes:
2 == 2 # => true 2 == 4 # => false However, by default, an Object doesn't know how to compare itself to other objects. For instance, if you define a new class, Fraction: class Fraction attr_reader :numerator, :denominator def initialize(numerator, denominator) @numerator, @denominator = [numerator, denominator] end end Fraction.new(3, 6) == Fraction.new(1, 2) # => false YOU have to write your own == method if you want to compare your classes with '==' class Fraction # ... def ==(other) # first, check if we're comparing two fractions, #comparing two different types of objects should return false return false unless (other.is_a?(Fraction)) (numerator / denominator) == (other.numerator / other.denominator) end end |
|
More on Equality in Ruby
|
== — generic "equality"
At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning. This is the most common comparison, and thus the most fundamental place where you (as the author of a class) get to decide if two objects are "equal" or not. === — case equality For class Object, effectively the same as calling #==, but typically overridden by descendants to provide meaningful semantics in case statements. This is incredibly useful. Examples of things which have interesting === implementations: Range Regex Proc (in Ruby 1.9) So you can do things like: case some_object when /a regex/ # The regex matches when 2..4 # some_object is in the range 2..4 when lambda {|x| some_crazy_custom_predicate } # the lambda returned true end |