[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Why is Array#to_f not defined?

Yukihiro Matsumoto

5/20/2008 8:16:00 AM

Hi,

In message "Re: Why is Array#to_f not defined?"
on Tue, 20 May 2008 17:05:04 +0900, Fredrik <fredjoha@gmail.com> writes:

|Ruby (1.8.6) seems to be missing numeric conversion methods for
|Arrays :

#to_f converts the receiver to the float itself.

|class Array
| def to_f
| self.map { |i| i.to_f }
| end
|end

The above code converts the elements in the array. That should be
named differently. Surely this is the reason. Try

ary.map(&:to_f)

if you have newer Ruby.

matz.

3 Answers

Fredrik

5/20/2008 8:30:00 AM

0

I see... I understand that it is not following the rule of "converting
the receiver to a float", but I would say that it follows the
"principle of least surprise".

Of course it is not possible to convert an Array to a Float in any
meaningful way, so to convert each element into a Float is the
behaviour I am expecting.

Well... that's my thinking anyway.

Fredrik

Robert Klemme

5/20/2008 8:52:00 AM

0

2008/5/20 Fredrik <fredjoha@gmail.com>:
> I see... I understand that it is not following the rule of "converting
> the receiver to a float", but I would say that it follows the
> "principle of least surprise".

That may be true for you, but it is not for me - and apparently others as well.

> Of course it is not possible to convert an Array to a Float in any
> meaningful way, so to convert each element into a Float is the
> behaviour I am expecting.

Well, Array#to_f could be defined like this:

class Array
alias :to_i :size
def to_f; to_i.to_f end
end

This is much more meaningful to me than making to_f a conversion of
each element to float. Note, I do not advocate this at all - all I am
saying is that there are more meaningful implementations of to_f than
the one you propose.

> Well... that's my thinking anyway.

Exactly. :-)

Kind regards

robert


--
use.inject do |as, often| as.you_can - without end

Alex MDC

5/20/2008 1:19:00 PM

0

[Note: parts of this message were removed to make it a legal post.]

>
> Of course it is not possible to convert an Array to a Float in any
> meaningful way, so to convert each element into a Float is the
> behaviour I am expecting.


But an array of floats isn't a float... (: