對抗垃圾信!請您點這裡:

我的E-mail:
我的Skype:My status

2007年4月30日

Array.longest ( Array.which_long?修改版 )

感謝在Ruby-talk上的:

Chris Carter
David A. Black
Harry
Robert Dober
James Edward
:)
原本的程式碼太長,而且使用內建的功能組合起來就好
再者,原本的程式會把陣列的元素強制轉型為String

新的程式碼為:
class Array
  def longest
    # Harry <http://www.kakueki.com/ruby/list.html>
    self.select{|r| r.to_s.size == self.max{|x, y| x.to_s.size <=> y.to_s.size}.to_s.size}
  end
end
這個程式是由Harry所寫出的,底下轉貼原文:

On 4/29/07, Billy Hsu <ruby.maillist@gmail.com> wrote:
> Thanks for your reply, I learned more on this thread :P
> But I have a question:
> If I have an array contain:
>   ary = [1, 12, 234, "456"]
> there has two elements which size is 3, but the longest method just returned
> one of them.
> I can't solve it :(
>

Is this what you are looking for?
Do you want all longest elements?

big = [1, 12, 234,45,978, "456"].max {|x,y| x.to_s.size <=> y.to_s.size}
p [1, 12, 234,45,978, "456"].select {|r| r.to_s.size == big.to_s.size}
由於Harry不喜歡被張貼信箱,因此我將他的網站給貼上來:
http://www.kakueki.com/ruby/list.html
A Look into Japanese Ruby List in English

再一次謝謝Harry的幫助:)
也謝謝其他人,讓我學到許多東西:D
Thanks again and again!!

CFC --


沒有留言: