Resources



examples/restrict_type_in_code_for_struct_attribute_fixed.cr
struct Person
  getter first : String
  getter family : String?

  def initialize(@first)
  end

  def initialize(@first, @family)
  end
end

if Random.rand < 0.5
  prs = Person.new("Foo")
else
  prs = Person.new("Foo", "Bar")
end

family = prs.family
if family.nil?
  puts "nil"
else
  puts "not nil"
  puts family.size
end

if family = prs.family
  puts "not nil"
  puts family.size
else
  puts "nil"
end

examples/restrict_type_in_code.cr
if Random.rand < 0.5
  x = "abc"
else
  x = nil
end

if x.nil?
  puts "nil"
else
  puts x
  puts x.size
end

examples/restrict_type_in_code_for_hash_fixed.cr
if Random.rand < 0.5
  prs = {
    "name"  => "Foo",
    "title" => "Manager",
  }
else
  prs = {
    "name"  => "Foo",
    "title" => nil,
  }
end

p! prs

title = prs["title"]
if title.nil?
  puts "nil"
else
  puts "not nil"
  puts title.size
end

if title = prs["title"]
  puts "not nil"
  puts title.size
else
  puts "nil"
end

examples/restrict_type_in_code_for_struct_attribute_broken.cr
struct Person
  getter first : String
  getter family : String?

  def initialize(@first)
  end

  def initialize(@first, @family)
  end
end

if Random.rand < 0.5
  prs = Person.new("Foo")
else
  prs = Person.new("Foo", "Bar")
end

if prs.family.nil?
  puts "nil"
else
  puts "not nil"
  puts prs.family.size
end

examples/type_inference_from_struct.cr
struct Dog
  getter name : String
  getter owner : String

  def initialize(@name, @owner)
  end
end

struct Cat
  getter name : String
  getter staff : String

  def initialize(@name, @staff)
  end
end

if Random.rand < 0.5
  animal = Dog.new("Gin", "Foo")
else
  animal = Cat.new("Tonic", "Bar")
end

p! animal
p! animal.class

# if animal.class == Cat
#  p! animal.staff
# else
#  p! animal.owner
# end

if animal.is_a?(Cat)
  p! animal.staff
else
  p! animal.owner
end

case animal
when Cat
  puts "cat"
  p! animal.staff
when Dog
  puts "dog"
  p! animal.owner
else
  puts "other"
end

examples/restrict_type_in_code_for_hash_broken.cr
if Random.rand < 0.5
  prs = {
    "name"  => "Foo",
    "title" => "Manager",
  }
else
  prs = {
    "name"  => "Foo",
    "title" => nil,
  }
end

p! prs

if prs["title"].nil?
  puts "nil"
else
  puts "not nil"
  puts prs["title"].size
end

examples/code_executed.cr
puts "Hello Crystal!"

class Hello
  puts "Hello from class"
end

struct My
  puts "Hello from struct"
end