1

I'm familiar with type annotations in Ruby. However, no where have found a mention about nilable types. That is, something similar to this:

class Merchant
  attr_reader token: String # never nil
  attr_reader name: String # how to signal it that it may be nil? 
  [.......]
end

And vise versa: I want to be able to describe a type which doesn't allow nil values.

Is that possible? How?

update1:

irb(main):009:0> tp1 = String
=> String
irb(main):010:0> v1 = "fdsafds"
=> "fdsafds"
irb(main):011:0> tp1 === v1
=> true
irb(main):012:0> tp2 = String?
Traceback (most recent call last):
        1: from (irb):12:in `<main>'
NoMethodError (undefined method `String?' for main:Object)
Did you mean?  String

Why does it fail?

michika
  • 11
  • 2

1 Answers1

2

You can see an example of this right on the landing page of RBS:

attr_reader reply_to: Message? # `?` means optional type: `#reply_to` can be `nil`

And more specifically, it is in the Syntax documentation:

Optional type

Optional type denotes a type of value or nil.

Integer?
Array[Integer?]

So, for your case, that would be

attr_reader name: String?
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653