abstract class Object

Overview

Object is the base type of all Crystal objects.

Included Modules

Direct Known Subclasses

Defined in:

object.cr
primitives.cr
json/any.cr
json/to_json.cr
colorize.cr
spec/expectations.cr
yaml/any.cr
yaml/to_yaml.cr

Class Method Summary

Instance Method Summary

Macro Summary

Instance methods inherited from module Spec::ObjectExtensions

should(expectation, file = __FILE__, line = __LINE__) should, should_not(expectation, file = __FILE__, line = __LINE__) should_not

Instance methods inherited from module Colorize::ObjectExtensions

colorize(fore)
colorize
colorize

Class Method Detail

def self.==(other : Class) #

[View source]
def self.===(other) #

[View source]
def self.cast(other) : self #

Casts other to this class.

This is the same as using as, but allows the class to be passed around as an argument. See the documentation on as for more information.

klass = Int32
number = [99, "str"][0]
typeof(number)             # => (String | Int32)
typeof(klass.cast(number)) # => Int32

[View source]
def self.clone #

[View source]
def self.dup #

[View source]
def self.from_json(string_or_io, root : String) : self #

Deserializes the given JSON in string_or_io into an instance of self, assuming the JSON consists of an JSON object with key root, and whose value is the value to deserialize.

Int32.from_json(%({"main": 1}), root: "main").should eq(1)

[View source]
def self.from_json(string_or_io) : self #

Deserializes the given JSON in string_or_io into an instance of self. This simply creates a parser = JSON::PullParser and invokes new(parser): classes that want to provide JSON deserialization must provide an def initialize(parser : JSON::PullParser method.

Int32.from_json("1")                # => 1
Array(Int32).from_json("[1, 2, 3]") # => [1, 2, 3]

[View source]
def self.from_yaml(string : String) : self #

[View source]
def self.hash #

[View source]
def self.inspect(io) #

[View source]
def self.name : String #

Returns the name of this class.

String.name # => "String"

[View source]
def self.nilable? #

Returns true if this class is Nil.

Int32.nilable? # => false
Nil.nilable?   # => true

[View source]
def self.to_s(io) #

[View source]
def self.|(other : U.class) forall U #

Returns the union type of self and other.

Int32 | Char # => (Int32 | Char)

[View source]

Instance Method Detail

def !=(other) #

Returns true if this object is not equal to other.

By default this method is implemented as !(self == other) so there's no need to override this unless there's a more efficient way to do it.


[View source]
def !~(other) #

Shortcut to !(self =~ other)


[View source]
abstract def ==(other) #

Returns true if this object is equal to other.

Subclasses override this method to provide class-specific meaning.


[View source]
def ===(other : JSON::Any) #

[View source]
def ===(other : YAML::Any) #

[View source]
def ===(other) #

Case equality.

The #=== method is used in a case ... when ... end expression.

For example, this code:

case value
when x
  # something when x
when y
  # something when y
end

Is equivalent to this code:

if x === value
  # something when x
elsif y === value
  # something when y
end

Object simply implements #=== by invoking #==, but subclasses (notably Regex) can override it to provide meaningful case-equality semantics.


[View source]
def =~(other) #

Pattern match.

Overridden by descendants (notably Regex and String) to provide meaningful pattern-match semantics.


[View source]
def class #

Returns the runtime Class of an object.

1.class       # => Int32
"hello".class # => String

Compare it with typeof, which returns the compile-time type of an object:

random_value = rand # => 0.627423
value = random_value < 0.5 ? 1 : "hello"
value         # => "hello"
value.class   # => String
typeof(value) # => Int32 | String

[View source]
def crystal_type_id #

:nodoc


[View source]
abstract def dup #

Returns a shallow copy of this object.

As a convention, .clone is the method used to create a deep copy of an object, but this logic isn't defined generically for every type because cycles could be involved, and the clone logic might not need to clone everything.

Many types in the standard library, like Array, Hash, Set and Deque, and all primitive types, define #dup and .clone.


[View source]
abstract def hash #

Generates an Int hash value for this object.

This method must have the property that a == b implies a.hash == b.hash.

The hash value is used along with #== by the Hash class to determine if two objects reference the same hash key.


[View source]
def inspect(io : IO) #

Appends a string representation of this object to the given IO object.

Similar to #to_s(io), but usually appends more information about this object.


[View source]
def inspect #

Returns a String representation of this object.

Similar to #to_s, but usually returns more information about this object.

Classes must usually not override this method. Instead, they must override #inspect(io), which must append to the given IO object.


[View source]
def itself #

Return self.

str = "hello"
str.itself.object_id == str.object_id # => true

[View source]
def not_nil! #

Returns self. Nil overrides this method and raises an exception.


[View source]
def tap(&block) #

Yields self to the block, and then returns self.

The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain.

(1..10).tap { |x| puts "original: #{x.inspect}" }
       .to_a.tap { |x| puts "array: #{x.inspect}" }
            .select { |x| x % 2 == 0 }.tap { |x| puts "evens: #{x.inspect}" }
                                      .map { |x| x*x }.tap { |x| puts "squares: #{x.inspect}" }

[View source]
def to_json #

[View source]
def to_pretty_json(indent : String = " ") #

[View source]
def to_pretty_json(io : IO, indent : String = " ") #

[View source]
def to_s #

Returns a string representation of this object.

Descendants must usually not override this method. Instead, they must override #to_s(io), which must append to the given IO object.


[View source]
abstract def to_s(io : IO) #

Appends a String representation of this object to the given IO object.

An object must never append itself to the io argument, as this will in turn call #to_s(io) on it.


[View source]
def to_yaml(io : IO) #

[View source]
def to_yaml #

[View source]
def try(&block) #

Yields self. Nil overrides this method and doesn't yield.

This method is useful for dealing with nilable types, to safely perform operations only when the value is not nil.

# First program argument in downcase, or nil
ARGV[0]?.try &.downcase

[View source]

Macro Detail

macro def_clone #

Defines a .clone method that returns a copy of this object with all instance variables cloned (.clone is in turn invoked on them).


[View source]
macro def_equals(*fields) #

Defines an #== method by comparing the given fields.

The generated #== method has a self restriction.

class Person
  def initialize(@name, @age)
  end

  # Define a `==` method that compares @name and @age
  def_equals @name, @age
end

[View source]
macro def_equals_and_hash(*fields) #

Defines #hash and #== method from the given fields.

The generated #== method has a self restriction.

class Person
  def initialize(@name, @age)
  end

  # Define a hash method based on @name and @age
  # Define a `==` method that compares @name and @age
  def_equals_and_hash @name, @age
end

[View source]
macro def_hash(*fields) #

Defines a #hash method computed from the given fields.

class Person
  def initialize(@name, @age)
  end

  # Define a hash method based on @name and @age
  def_hash @name, @age
end

[View source]
macro delegate(*methods, to object) #

Delegate methods to to.

Note that due to current language limitations this is only useful when no captured blocks are involved.

class StringWrapper
  def initialize(@string : String)
  end

  delegate downcase, to: @string
  delegate gsub, to: @string
  delegate empty?, capitalize, to: @string
end

wrapper = StringWrapper.new "HELLO"
wrapper.downcase       # => "hello"
wrapper.gsub(/E/, "A") # => "HALLO"
wrapper.empty?         # => false
wrapper.capitalize     # => "Hello"

[View source]
macro forward_missing_to(delegate) #

Forwards missing methods to delegate.

class StringWrapper
  def initialize(@string)
  end

  forward_missing_to @string
end

wrapper = StringWrapper.new "HELLO"
wrapper.downcase       # => "hello"
wrapper.gsub(/E/, "A") # => "HALLO"

[View source]
macro getter(*names) #

Defines getter methods for each of the given arguments.

Writing:

class Person
  getter name
end

Is the same as writing:

class Person
  def name
    @name
  end
end

The arguments can be string literals, symbol literals or plain names:

class Person
  getter :name, "age"
end

If a type declaration is given, an instance variable with that name is declared with that type.

class Person
  getter name : String
end

Is the same as writing:

class Person
  @name : String

  def name : String
    @name
  end
end

The type declaration can also include an initial value:

class Person
  getter name : String = "John Doe"
end

Is the same as writing:

class Person
  @name : String = "John Doe"

  def name : String
    @name
  end
end

An assignment can be passed too, but in this case the type of the instance variable must be easily inferrable from the initial value:

class Person
  getter name = "John Doe"
end

Is the same as writing:

class Person
  @name = "John Doe"

  def name : String
    @name
  end
end

If a block is given to the macro, a getter is generated with an instance variable that is lazily initialized with the block's contents:

class Person
  getter(birth_date) { Time.now }
end

Is the same as writing:

class Person
  def birth_date
    @birth_date ||= Time.now
  end
end

[View source]
macro getter!(*names) #

Defines raise-on-nil and nilable getter methods for each of the given arguments.

Writing:

class Person
  getter! name
end

Is the same as writing:

class Person
  def name?
    @name
  end

  def name
    @name.not_nil!
  end
end

The arguments can be string literals, symbol literals or plain names:

class Person
  getter! :name, "age"
end

If a type declaration is given, an instance variable with that name is declared with that type, as nilable.

class Person
  getter! name : String
end

is the same as writing:

class Person
  @name : String?

  def name?
    @name
  end

  def name
    @name.not_nil!
  end
end

[View source]
macro getter?(*names) #

Defines query getter methods for each of the given arguments.

Writing:

class Person
  getter? happy
end

Is the same as writing:

class Person
  def happy?
    @happy
  end
end

The arguments can be string literals, symbol literals or plain names:

class Person
  getter? :happy, "famous"
end

If a type declaration is given, an instance variable with that name is declared with that type.

class Person
  getter? happy : Bool
end

is the same as writing:

class Person
  @happy : Bool

  def happy? : Bool
    @happy
  end
end

The type declaration can also include an initial value:

class Person
  getter? happy : Bool = true
end

Is the same as writing:

class Person
  @happy : Bool = true

  def happy? : Bool
    @happy
  end
end

An assignment can be passed too, but in this case the type of the instance variable must be easily inferrable from the initial value:

class Person
  getter? happy = true
end

Is the same as writing:

class Person
  @happy = true

  def happy?
    @happy
  end
end

[View source]
macro property(*names) #

Defines property methods for each of the given arguments.

Writing:

class Person
  property name
end

Is the same as writing:

class Person
  def name=(@name)
  end

  def name
    @name
  end
end

The arguments can be string literals, symbol literals or plain names:

class Person
  property :name, "age"
end

If a type declaration is given, an instance variable with that name is declared with that type.

class Person
  property name : String
end

Is the same as writing:

class Person
  @name : String

  def name=(@name)
  end

  def name
    @name
  end
end

The type declaration can also include an initial value:

class Person
  property name : String = "John Doe"
end

Is the same as writing:

class Person
  @name : String = "John Doe"

  def name=(@name : String)
  end

  def name
    @name
  end
end

An assignment can be passed too, but in this case the type of the instance variable must be easily inferrable from the initial value:

class Person
  property name = "John Doe"
end

Is the same as writing:

class Person
  @name = "John Doe"

  def name=(@name : String)
  end

  def name
    @name
  end
end

If a block is given to the macro, a property is generated with an instance variable that is lazily initialized with the block's contents:

class Person
  property(birth_date) { Time.now }
end

Is the same as writing:

class Person
  def birth_date
    @birth_date ||= Time.now
  end

  def birth_date=(@birth_date)
  end
end

[View source]
macro property!(*names) #

Defines raise-on-nil property methods for each of the given arguments.

Writing:

class Person
  property! name
end

Is the same as writing:

class Person
  def name=(@name)
  end

  def name?
    @name
  end

  def name
    @name.not_nil!
  end
end

The arguments can be string literals, symbol literals or plain names:

class Person
  property! :name, "age"
end

If a type declaration is given, an instance variable with that name is declared with that type, as nilable.

class Person
  property! name : String
end

Is the same as writing:

class Person
  @name : String?

  def name=(@name)
  end

  def name?
    @name
  end

  def name
    @name.not_nil!
  end
end

[View source]
macro property?(*names) #

Defines query property methods for each of the given arguments.

Writing:

class Person
  property? happy
end

Is the same as writing:

class Person
  def happy=(@happy)
  end

  def happy?
    @happy
  end
end

The arguments can be string literals, symbol literals or plain names:

class Person
  property? :happy, "famous"
end

If a type declaration is given, an instance variable with that name is declared with that type.

class Person
  property? happy : Bool
end

Is the same as writing:

class Person
  @happy : Bool

  def happy=(@happy)
  end

  def happy?
    @happy
  end

  def happy
    @happy.not_nil!
  end
end

The type declaration can also include an initial value:

class Person
  property? happy : Bool = true
end

Is the same as writing:

class Person
  @happy : Bool = true

  def happy=(@happy : Bool)
  end

  def happy? : Bool
    @happy
  end
end

An assignment can be passed too, but in this case the type of the instance variable must be easily inferrable from the initial value:

class Person
  property? happy = true
end

Is the same as writing:

class Person
  @happy = true

  def happy=(@happy)
  end

  def happy?
    @happy
  end
end

[View source]
macro setter(*names) #

Defines setter methods for each of the given arguments.

Writing:

class Person
  setter name
end

Is the same as writing:

class Person
  def name=(@name)
  end
end

The arguments can be string literals, symbol literals or plain names:

class Person
  setter :name, "age"
end

If a type declaration is given, an instance variable with that name is declared with that type.

class Person
  setter name : String
end

is the same as writing:

class Person
  @name : String

  def name=(@name : String)
  end
end

The type declaration can also include an initial value:

class Person
  setter name : String = "John Doe"
end

Is the same as writing:

class Person
  @name : String = "John Doe"

  def name=(@name : String)
  end
end

An assignment can be passed too, but in this case the type of the instance variable must be easily inferrable from the initial value:

class Person
  setter name = "John Doe"
end

Is the same as writing:

class Person
  @name = "John Doe"

  def name=(@name)
  end
end

[View source]