Is everything an object in ruby? - ruby

Is everything in ruby an object? Does this include Fixnums?

Depends on what you mean by "everything". Fixnums are, as the others have demonstrated. Classes also are, as instances of class Class. Methods, operators and blocks aren't, but can be wrapped by objects (Proc). Simple assignment is not, and can't. Statements like while also aren't and can't. Comments obviously also fall in the latter group.
Most things that actually matter, i.e. that you would wish to manipulate, are objects (or can be wrapped in objects).

Yes. Fixnum is a class, which inherits from Integer, which inherits from Numeric, which finally inherits from Object.
Or, why don't you just ask it? :)
1.is_a? Object # => true
1.class # => Fixnum
Fixnum.is_a? Object # => true
Reading the Ruby info and documentation on the website is a good idea too.

Practically everything in Ruby is an Object, with the exception of control structures. Whether or not under the covers a method, code block or operator is or isn't an Object, they are represented as Objects and can be thought of as such.
Take a code block for example:
def what_is(&block)
puts block.class
puts block.is_a? Object
end
> what_is {}
Proc
true
=> nil
Or for a Method:
class A
def i_am_method
"Call me sometime..."
end
end
> m = A.new.method(:i_am_method)
> m.class
Method
> m.is_a? Object
true
> m.call
"Call me sometime..."
And operators (like +, -, [], <<) are implemented as methods:
class String
def +
"I'm just a method!"
end
end
For people coming into programming for the first time, what this means in a practical sense is that all the rules that you can apply to one kind of Object can be extended to others. You can think of a String, Array, Class, File or any Class that you define as behaving in much the same way. This is one of the reasons why Ruby is easier to pick up and work with than some other languages.

Yes everything is an object in ruby, and that includes Fixnum

Ruby doen't have any primitives (like int, char etc in java), so every value (anything that can sit on the right of an assignment statement) is an object. However, control statements, methods, and other features of the language syntax aren't.

Yup.
> Fixnum.is_a?(Object) #=> true
To see the chain of inheritance:
> pp Fixnum.ancestors
[Fixnum,
Integer,
Precision,
Numeric,
Comparable,
Object,
...
Kernel]
=> nil

Related

Ruby function called via the dot

I want to call a function named my_format_number like:
num = 5.5
formated_num = num.my_format_number
How can I do that in Ruby? And what is the name of these types of functions?
what is the name of these types of functions?
In object oriented programming (independent of programming language), a function that is bound to an object (often through the object's class) is called a 'method'. Some Ruby documentation calls all functions 'methods', though. For the sake of distinction, I'll use 'method' only to mean bound functions and keep referring to functions in general as 'functions'.
A function not bound to an object is usually called a 'free function'.
The object to which a method is bound is called the method's 'receiver'.
How can I do that in Ruby?
In Ruby, methods are always instance methods: They are defined on the class, but act on instances of the class. (I.e., the receiver must be an instance.) Other than in C/C++ or Java, all values in Ruby are objects (instances of classes), so every value has a class.
Class? What class?
A class is the type of a value/object/instance. It determines (to some degree) the value's semantic, as well as the methods available on that value.
What is the class of 5.5? Let's find out:
(5.5).class()
# => Float
(The shorter 5.5.class would have worked, too, but is a bit harder to understand.)
Float is Ruby's built-in class for floating point numbers.
Modifying the Float class
Class definitions in Ruby can be split up and distributed. Each chunk will have effect after having been interpreted, additional to the chunks already in effect, which means you can modify classes at runtime. This is known as 'monkey patching' or 're-opening a class'.
Let's re-open the Float class and add the my_format_number method. I decided it shall return a string:
class Float
def my_format_number
return "The number is #{self} and #{self} is the number."
end
end
(The return in front of the string could be skipped, as Ruby functions implicitly return the last expression they evaluate.)
Now you can call your new method on all Float values:
num = 5.5
formatted_num = num.my_format_number()
puts(formatted_num)
# The number is 5.5 and 5.5 is the number.
We don't even need variables and can invoke the method directly on value literals:
puts 7.8.my_format_number
# The number is 7.8 and 7.8 is the number.
It won't work for all numbers, though:
100.my_format_number
# NoMethodError: undefined method `my_format_number' for 100:Fixnum
# from (irb):15
# from :0
That's because we defined the number of Float and 100 is (as the error message tells us) not a Float but a Fixnum (a special kind of Integer).
Modifying several related classes at once
You could of course now also define the function of Fixnum. But there are numbers that are neither Fixnums nor Floats. So it would make sense to have the function at some central place.
We could monkey patch Ruby's master class, Object. But that would allow
"foobar".my_format_number
to return "The number is foobar and foobar is the number.", which doesn't make sense, as foobar is not a number. I'd only want our method to format numbers.
Let's see how the classes of Fixnum are structured:
Fixnum.superclass()
# => Integer
Fixnum.superclass().superclass() # equivalent to `Integer.superclass`
# => Numeric
Fixnum.superclass().superclass().superclass() # equivalent to `Numeric.superclass`
# => Object
The superclass method only gives us one direct ancestor. Using Ruby modules, multiple inheritance is possible, thus we can get some more results like so:
Fixnum.ancestors
# => [Fixnum, Integer, Precision, Numeric, Comparable, Object, Kernel]
Let's see what the overlap is with
Float.ancestors()
# => [Float, Precision, Numeric, Comparable, Object, Kernel]
Comparable is probably more general than just numbers, while Precision might be too specific or even somewhat unrelated. (It's probably a module.) Let's modify Numeric thus, which (guessing from it's name) sounds like the right level of abstraction. Indeed, the documentation calls it
The top-level number class.
Therefore, very similar to before,
class Numeric
def my_format_number
return "The number is #{self} and #{self} is the number."
end
end
And now
100.my_format_number
# => "The number is 100 and 100 is the number."
If you want to know all the classes to which we've added the method in this second monkey-patching, have a look at Look up all descendants of a class in Ruby.
class Float
def my_format_number
...
end
end
I thought I'd add a simple example that demonstrates how to make and call a method using the .
def plus_two
self + 2
end
2.plus_two
=> 4

When to use (:method) or (&:method)

Why does: respond_to? in:
class Wolf
def howl; end
end
Wolf.new.respond_to?(:howl) # => true
not require & while map in:
["1", "2", "3"].map(&:to_i) # => [1, 2, 3]
does? Also, are there any technical names for this?
When you say :method, you're using some nice syntactical sugar in ruby that creates a new Symbol object. When you throw an ampersand before it (&:method), you're using another piece of sugar. This invokes the to_proc method on the symbol.
So, these two things are identical:
method_proc = &:method
sym = :method
method_proc = method.to_proc
What's the difference between that and the other usage? Well, respond_to? has a single argument -- a symbol. So we can pass :method and be all fine and dandy. (Interestingly, objects do respond to the method named method, but that's a far more confusing question).
By comparison, Enumerable's iterators (like map, select, etc) accept a block. When we pass a Proc, it is interpreted properly as that block. So, these two pieces of code are equivalent:
[1,2,3].map { |i| i.even? }
[1,2,3].map(&:even?)
This equivalence is a little confusing, because of course Symbol has no idea that there's an even? method somewhere. To play around with it, I used evenproc = :even?.to_proc to inspect the resulting proc. It's implemented in C (at least in MRI ruby), and isn't willing to give up its source. However, its arity is -1, which means that it accepts one optional arg. My best guess is that it does something like this:
def to_proc
method_name = self.to_s
->(a) { a.send(method_name) }
end
I could dig further, but I think we've already gone way past the question. ;) Good luck!

How can I make a custom Ruby type behave like a string?

If I have a custom Ruby class representing some string type, as in
class MyString
end
Which functions should I implement in order to make the following use cases possible:
Passing a Ruby string whenever a MyString is expected
Passing a MyString whenever a Ruby string is expected
Comparing a Ruby string with a MyString value (it shouldn't matter whether I use s == t or t == s).
I saw various interesting functions like to_s, cmp, == and eq already, but it's not clear to me when each of them is called.
My concrete use case is that I'm writing a Ruby extension using the C API which exposes functions taking (and returning) values of a custom string type (QString, to be precise) which my extension also registers. However, I'd like to make those custom strings behave as intuitive as possible. Unfortunately I can't just return Ruby strings from my C code since it should be possible to call Qt methods on the strings.
There are at least three approaches:
class MyString < String; ...; end
Define #to_s
Define #to_str
Doing both #2 and #3 will make the object act very much like a real String even if it isn't a subclass.
#to_s is an explicit converter, meaning it must appear in Ruby code to work.
#to_str is an implicit converter, meaning the Ruby interpreter will attempt to call it when it wants a String but is given something else.
Update:
Here is an example of some fun you can have with to_str:
begin
open 1, 'r'
rescue TypeError => e
p e
end
class Fixnum
def to_str; to_s; end
end
open 1, 'r'
When run, the first open fails with TypeError but the second proceeds to looking for 1.
#<TypeError: can't convert Fixnum into String>
fun.rb:9:in `initialize': No such file or directory - 1 (Errno::ENOENT)
from fun.rb:9:in `open'
Although it's tempting to sub-class String to give it a new initialize method that will import these QString-type strings, you may just want to tack on an extension to String that helps with the conversion so you don't have to re-implement a version of String itself.
For instance, with two methods you could pretty much have this done:
class String
def self.from_qstring(qstring)
new(...)
end
def to_qstring
# ...
end
end
Having multiple storage types for String is not going to be a problem until you start comparing them, but given that Ruby's String is quite robust, writing a work-alike is difficult.
It's not generally a good idea to subclass classes that were built by someone else in Ruby, because too many things can go wrong. (You might, for example, override an internal method without knowing it.)
1) define Mystring.to_s to get automatic conversion from a Mystring to a String.
2) Not sure what you mean by this. If you want a String method that returns a Mystring, you will have to monkey-patch String:
Class String
def to_mystring
return Mystring.new(self)
end
end
3) to get t == s (assuming s is an instance of String and t an instance of Mystring) define <=>. To get s == t you will have to monkey patch String again, though.
Since I was looking for something similar, but none of the other answers worked for me, I'll post what did work for me.
Found in this blog post which discourage the use of inheriting String and instead use simple delegator.
Inheriting from SimpleDelegator create an object which delegate everything to a string of your choice but on which you add behavior as you see fit.
class ChunkyBacon < SimpleDelegator
def initialize(content)
#content = content
super #content
end
def chunky_bacon?
#content == 'chunky_bacon'
end
end
test = ChunkyBacon.new('choco pizza') # => 'choco pizza'
test.chunky_bacon? # => false

Is there a ruby equivalent to the Scala Option?

How do I model an optional value in ruby? Scala has Option[], which is what I'm looking for in ruby.
There's no equivalent in the standard library. You have to define your own. See this article.
I'm not a Ruby expert, but I don't think there is an Option equivalent. As Ruby is object oriented, nothing stops you from writing your own implementation, but it won't be as useful as in a statically typed language, where the compiler forces you to do a proper check for the empty option, which is one of the main points for using this construct. Of course there are other advantages, like the possibility to chain Option values in several ways.
Have you checked out the Rumonade gem? It gives you an Option class modeled on scala.
require 'rumonade'
[nil, 1, 123].map { |v| Option(v) }
=> [None, #<Rumonade::Some:0x7f2589297768 #value=1>, #<Rumonade::Some:0x7f2589297740 #value=123>]
[nil, 1, 123].map { |v| Option(v).map { |n| n.to_s }.select { |s| s.size > 2 } }.flatten
=> ["123"]
There is an example of a Maybe class in nkpart's adt library under examples/common_adts.rb. There are also other example ADTs and the library makes it easier to define your own.
I have just pushed a gem called nil_be_gone that gives you an Optional that you can wrap objects with. It implements method_missing to check whether the value of the Optional is nil and if so simply return another Optional wrapped nil value, otherwise it calls the method on the object and wraps it again.
nil_be_gone implements bind as and_then which allows you to chain operations on Optional types, it's return methods which retrieves the value from Optional is value and the unit operation which wraps an object in the monad is defined by self.from_value.
I don't know Scala, so I can't assert that's your answer:
In ruby, when you call a method, you can define a default value for a param:
def foo(i_am_mandatory, i_am_optionnal = :banga)
puts i_am_optionnal
end
foo(:pouet, :plip)
=> :plip
foo(:pouet)
=> :banga
In that example, you can omit i_am_optionnal, which has a default value.
HTH.

Any good reason for Ruby to have == AND eql? ? (similarly with to_a and to_ary)

I know eql? is used by Hashes to see if an object matches a key*, and you do
def ==(rb)
if you want to support the == operator, but there must be a good reason that Hashes don't use == instead. Why is that? When are you going to have definitions for == and eql? that are not equivalent (e.g. one is an alias to the other) ?
Similarly, why have to_ary in addition to to_a?
This question came up in response to an answer someone gave me on another question.
* Of course, a Hash also assumes eql? == true implies that the hashes codes are equal.
Also, is it basically a terribly idea to override equal? ?
== checks if two values are equal, while eql? checks if they are equal AND of the same type.
irb(main):001:0> someint = 17
=> 17
irb(main):002:0> someint == 17
=> true
irb(main):003:0> someint.eql? 17
=> true
irb(main):004:0> someint.eql? 17.0
=> false
irb(main):005:0> someint == 17.0
=> true
irb(main):006:0>
as you can see above, eql? will also test if both values are the same type. In the case of comparing to 17.0, which equates to false, it is because someint was not a floating point value.
I don't know the reasoning for this particular choice in ruby, but I'll just point out that equality is a difficult concept.
Common Lisp, for example has eq, eql, equal, equalp, and for that matter =
It can be very useful to be able to tell the difference between two references to the same object, two different objects of the same type with the same value, two objects with the same value but of different types, etc. How many variations make sense depends on what makes sense in the language.
If I recall it correctly (I don't use ruby), rubys predicates are implementing three of these cases
== is equality of value
eql? is equality of value and type
equal? is true only for the same object
This mentions that to_a and to_ary (and to_s and to_str , and to_i and to_int) have different levels of strictness. For example,
17.to_s
makes sense,
17.to_str
doesn't.
It seems that there is no to_ary method for the Hash class (no to_a), but for the Array class, to_a and to_ary have different behavior :
to_a :
Returns self. If called on a subclass of Array, converts the receiver to an Array object.
to_ary :
Returns self.
The answers above more that answer about eql? but here is something on to_a and to_ary.
In Ruby's duck-typing scheme, objects can be converted two ways--loosely and firmly. Loose conversion is like saying:
Can foo represent itself as an array (to_a). This is what to_a, to_s, to_i and other single letter ones are for. So a String can represent itself as an array, so it implements to_a. Firm conversion says something very different: Is foo a string (to_ary). Note that this is not wheather the class of foo is String, but whether foo and strings are interchangeable--whether anywhere a string is expected a foo could be logically used. The example in my Ruby book is of a Roman numeral class. We can use a Roman numeral anywhere we could use a positive integer, so Roman can implement to_int.
Classes that have an are interchangeable relationship need to implement firm conversion, while loose is for almost all classes. Make sure not to use firm conversion where loose is right--code built into the interpreter will severely misunderstand you and you'll end up with bugs comparable to C++'s reinterpet_cast<>. Not good.

Resources