rubyisforfun/manuscript/021.txt

47 lines
1.8 KiB
Text
Raw Normal View History

2019-01-03 04:31:04 +01:00
## Everything Is An Object (Proof)
We know that `123.class` returns _Integer_, and `"blabla".class` returns _String_. But any object also has `is_a?` method, which returns _true_ or _false_, depending on parameter you're passing to this method:
{lang=ruby, line-numbers=off}
```ruby
$ irb
> 123.is_a?(Integer)
=> true
```
2019-01-03 04:45:11 +01:00
In example above we're calling `is_a?` method for `123` object and passing parameter `Integer`. Method returns true. In other words, `123` is a type of _Integer_. The similar way we can test if `123` is `String`:
2019-01-03 04:31:04 +01:00
2019-01-03 04:45:11 +01:00
{lang=ruby, line-numbers=off}
```ruby
$ irb
> 123.is_a?(String)
=> false
```
2019-01-05 06:36:19 +01:00
Answer is false, `123` is not _String_, but `"123"` (in quotes) is _String_:
2019-01-03 04:45:11 +01:00
{lang=ruby, line-numbers=off}
```ruby
$ irb
> "123".is_a?(String)
=> true
> "blabla".is_a?(String)
=> true
```
2019-01-05 06:36:19 +01:00
By calling `is_a?` we're kinda asking question in plain English "**Is** this **a**... ?", "Is this object a string?"
2019-01-03 04:45:11 +01:00
We've confirmed that `123` is _Integer_, and `"blabla"` is _String_. Now let's make sure integers and strings are objects:
{lang=ruby, line-numbers=off}
```ruby
$ irb
> 123.is_a?(Object)
=> true
> "blabla".is_a?(Object)
=> true
```
Great, numbers and strings are objects in Ruby! In other words, `123` is _Integer_ and _Object_ at the same time. And `"blabla"` is _String_ and _Object_ at the same time. In other words, there can be multiple objects, and objects _can implement_ multiple types.
2019-01-05 06:36:19 +01:00
We'll discuss later in this book what object really is. We don't need to remember `is_a?` method at the moment, how to call this method, and what it returns (in computer literature it is called "method signature", sometimes API - Application Program Interface). But it's worth remembering `.class`, so you can any time check the type of any object (or the type of result of some operation).