In programming world type casting and type conversion has completely
different meaning we all know. Now in ruby’s world which it supports?
Does ruby supports both or either of them?
With the below code what it did - casting or conversion?
because ruby is very strong typed, it does not have casting per se,
so without bad Hacks an object cant change its own type/class.
so to_i and others are always conversion.
but ruby has different kinds …
to_int is implicit conversion, but only exist for classes which are
already a number.
to_i is explicit conversion. it exist for other classes like String too
when the core defined methods wants an Integer for sample, ruby
automatic tries to call to_int, but not to_i for non-Integer
there are other pairs too:
to_ary - to_a
to_hash - to_h
to_str - to_s
because ruby is very strong typed, it does not have casting per se,
I disagree: there is no casting - but for other reasons: Ruby does not
have casting because it is dynamically typed. You cannot get into a
situation where you need to cast an expression to another type because
there is no static type information at all.
Unfortunately in C++ land the term “casting” is also often used for
“conversion” because that is done via the cast operator. I prefer to
use “cast” only for changes which do not affect the memory
representation, i.e. changing the type of reference in Java or
reinterpreting a bit pattern in memory as a different type.
so without bad Hacks an object cant change its own type/class.
Right.
so to_i and others are always conversion.
but ruby has different kinds …
to_int is implicit conversion, but only exist for classes which are
already a number.
to_i is explicit conversion. it exist for other classes like String too
when the core defined methods wants an Integer for sample, ruby
automatic tries to call to_int, but not to_i for non-Integer