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

我的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 --


2007年4月28日

Array.which_long? -- 剛出爐的函式

class Array
def which_long?
# Version 1.0
# Coded by CFC <>
# PLEASE DO NOT REMOVE THE COMMENT OF THIS FUNCTION, THANKS A LOT.
# Usage:
# ['a', 'ab', 'abc' 1234].which_long?
# => 1234
self.size.times{|i| self[i]=self[i].to_s}
max, long = 0, String.new
self.each{|item| item.size > max ? (max = item.size; long = item) : next}
long
end
end


以上是原始碼,使用方式如下:

puts ['a', 'ab', 'abc', 1234].which_long?
=> 1234

授權還沒定,不過大家還是可以拿去使用:P
請不要拿掉註解.. 謝謝

2007年4月24日

rubygems 0.9.2的問題

本文同步發佈至:http://blog.pixnet.net/zusocfc/post/4160285


升級Rubygems到0.9.2時,不論是安裝gem包還是升級gem包
都會產生一個Error:

ERROR:  While executing gem ... (NoMethodError)
    undefined method `refresh' for #<Hash:0xb799a478>

這個時候該怎麼辦呢?
根據這篇文章所寫:http://www.cnzxh.net/blog/Index.php?do=readArticle&articleId=145
我們可以做這個動作:

rm -f /usr/local/lib/ruby/gems/1.8/source_cache

經過測試後.. 真的就正常了..
所以如果你有出同樣問題 請照做吧:P
( 我想這問題只會發生在*nix系統上 )

2007年4月20日

大量帳號建置器 版本1跟版本2

先說好,跟往常一樣.. 到我Pixnet的網誌看會比較不頭痛:P
版本1可以不用寫群組名稱,但是程式碼好醜ˊˋ
版本2必須要有群組名稱,適用於學校(?)

版本1下載
版本2下載

版本1:

#!/usr/bin/env ruby
File.open(ARGV[0]) do |file|
  while a = file.gets
    a = a.chomp.split(/ /)
    print "username => #{a[0]} ", "password => #{a[1]} ", "group => #{a[2]}", "\n"
    a[2].nil? ? `useradd -m #{a[0]}` : `useradd -m -G #{a[2]} #{a[0]}`
    `echo #{a[0]}:#{a[1]} | chpasswd`
  end
end
exec "pwconv"

使用者清單寫法:

  帳號 密碼 群組

版本2:

#!/usr/bin/env ruby
require 'yaml'
YAML.load_file(ARGV[0]).each{ |grp|
  grp.each{ |usr|
    usr.each{ |i|
      info = i.chomp.split(/ /)
      `useradd -m -G #{grp[0]} #{info[0]}`
      `echo #{info[0]}:#{info[1]} | chpasswd`
    }
  }
}
`pwconv`

使用者清單寫法:

grp1:
  - usr1 pwd1
  - usr2 pwd2
grp2:
  - usr3 pwd3
  - usr4 pwd4
grp3:
  - usr5 pwd5
  - usr6 pwd6
使用方式都是:
./account list

程式授權.. 隨便啦