Skip to content

Instantly share code, notes, and snippets.

@marinados
Created February 10, 2016 15:07
Show Gist options
  • Save marinados/82f3c7b0166ad06b59b9 to your computer and use it in GitHub Desktop.
Save marinados/82f3c7b0166ad06b59b9 to your computer and use it in GitHub Desktop.
# to_i and to_int;
# to_s and to_str;
# to_a and to_ary;
# to_h and to_hash.
"string" + other #will call to_str on other, [1,2,3] + other will call #to_ary and so on (and will raise TypeError: no implicit conversion if object not responds to this methods);
"string" * other || [1,2,3] * other # will call #to_int on other;
a, b, c = *other # will call other to_ary (and, therefore, can be used to “unpack” custom collection objects—but also can cause unintended behavior, if other implements to_ary but was not thought as a collection);
some_method(*other) #—same as above, uses other#to_ary;
some_method(**other) #—new in Ruby 2, uses other#to_hash.
class Unicorn
attr_reader :name, :age
def initialize(name, age, wings)
@name, @age, @wings = name, age, wings
end
# erroneously defined for serialization instead of to_h
def to_hash
{species: 'Unicorn', name: name, age: age, wings: wings}
end
end
def set_options(**some_options)
p some_options
end
unicorn = Unicorn.new('Antoine', 5, 'yellow')
set_options(sth: 'something')
# ok, prints {sth: 'something'}
set_options(1)
# can't be called this way, raises helpful ArgumentError
set_options(unicorn)
# ooops, treats our unicorn as an options hash
# and prints {species: 'unicorn', name: name, age: age, wings: wings}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment