Sunday, August 31, 2008
Graphviz
Thursday, August 28, 2008
バランスボールってあり?
Programming Ruby 3 - New topics
- RSpec: write rspec first, then implement code
- Organize project: top/ ./bin ./lib/top ./test
- Use setup.rb for distributing project
- RubyGems: open rdoc for library: open $gemdoc/builder/.../rdoc/index.html
- Encoding: # encoding: utf-8/ over 7bit characters assume the source file encoding
- Input Output Encoding: File.open("filename", "r:iso-8859-1:utf-8:")
- irb: load "your ruby file with classes or methods" : you use the classes in irb session. also can edit the file after loaded.
- irb: use tab completion alot
- irb: use irb in irb to make a subsession: jobs, fg 0, kill 1
- irb: use irb with specific class: irb "wombat"
- Constant: Constant can define from the outside.
- Module: module_function: makes instance method module method also.
- Exception: rescue modifier: ["1","2.3",/pattern/].map {|v| Integer(v) rescue Float(v) rescue String(v)}
- Exception: retry can be used in rescue clause.
- methods(false): just show methods in the object; exclude superclasses'
- Duck typing: if you need check types: use obj#respond_to?
- type conversion: method coersion: 1.coerce(2.3) -> [2.3,1.0];define coerce method in your class correctly, you get arithmetic func with numbers.
- metaprogramming:module:ruby makes anonymous super class for a class, in which module is mixed in.
- metaprogramming:extend: when use extend to a obj, the module is included to an anonymous class of the obj.
- metaprogramming:extend: when use extend in a class, the module method become its class method. that means extend makes singleton method
Wednesday, August 27, 2008
Rubyのクラスはソフトのコーン
Tuesday, August 26, 2008
ソートプログラム
- 先頭から隣り合うデータを比較
- 大小が逆ならスワップ
- スワップした時は一つ前に戻ってまた比較
- これを繰り返す
1 #!/usr/local/bin/ruby
2 # encoding: utf-8
3 class Array
4 def thought
5 n = 0
6 until n == self.length - 1
7 if comp(n)
8 swap(n)
9 n -= 1 unless n < 0
10 redo unless n < 0
11 end
12 n += 1
13 end
14 self
15 end
16
17 private
18 def comp(n)
19 self[n] > self[n+1]
20 end
21
22 def swap(n)
23 self[n], self[n+1] = self[n+1], self[n]
24 end
25 end
26
27 a = [4,3,6,8,1,2,9,5,7,0,12,23,87,13,33,14,56,21,89,100,44,22]
28 p a.thought
Saturday, August 23, 2008
Friday, August 22, 2008
Programming Ruby 3rd - new topics
- IO.foreach('file') {|line| puts line}
- 'abcdefghi'.scan(/abc(..)(..).*/) # => [[cd],[ef]]
- StringIO: use string like io
- Network library: socket, net/http, open-uri
- Fiber: fiber is like a block object
- Thread: use thread local variable: Thread.new(arg) {|val| ...}
- Thread: threads.join can wait all
- Thread: thread variables: can store current thread to a hash: Thread.current["mycount"] = count
RSpecがいいかもしれない
このフレームワークは今までのように書いたコードを
後からテストするためのものではなく
先に仕様を書いてそれに合わせてコードを書くような開発方式を強いる
これをBDDとかTDDとかいうようだ
具体的には以下の手順になる
まずこれから書こうとしているコードの期待される出力を仕様として書く
その仕様をこれに関連付けてコードにする
テストしてみる(当然エラーが出る)
エラーがなくなるようにコードを書く
サンプル(階乗計算コード)
require "fact"
describe "Fact", "basic factorial" do
before(:each) do
@ts = Fact.new
end
it "should be 1 when 1!" do
@ts.fact(1).should == 1
end
it "should be 6 when 3!" do
@ts.fact(3).should == 6
end
it "should be 120 when 5!" do
@ts.fact(5).should == 120
end
end
今後なるべくBDDで開発してみよう
RSpec-1.1.4: Overview
http://rspec.info/
Wednesday, August 20, 2008
Programming Ruby 3rd - new topics
- expressions: method chain: def <<(other); total += other; self end
- expressions: define []=: def []=(*params); obj.[]=(1,2) # => [1,2]
- expressions: backticks also a method of Kernel, that can redefine.
- parallel assignment: f, *, l = 1,2,3,4,5 # f = 1, l = 5
- nested assignment: a, (b,c), d = 1,2,3,4 # a = 1, b = 2, c = nil, d = 3
- flip-flop function with range: while puts line if line=~/third/..line=~/fifth/
- flip-flop while if (($.==1)||line=~/eig/)..(($.==3)||line=~/nin/); print line
- redo if line.gsub!(/`(.*?)`/){eval($1)}
- ary.each do |val; outer-local|
- block local scope: [1,2,3].each {|a,b|} or {|a;b|}#b is local val of block
Ruby Block local
#!/usr/local/bin/ruby
# encoding: utf-8
s = 'yes'
total = 0
{a: 2, b: 3}.each do |v,k,s|
s = k**2
total += s
end
puts total
puts s
Tuesday, August 19, 2008
A blog theme candidate
- あるファイル上のデータ、例えば書籍データを読み込んで管理するプログラムを考える。
- 最初に配列とハッシュを使った例を示す。
- これらでのアクセスを示す。
- その問題点を示す。
- それからオブジェクトモデルを示す。
- そのアクセスと利点を示す。
Programming Ruby 3rd _new topics for me
- regexp: \p: encoding-aware
- regexp: &&: [a-z]&&[^aeiou] means match a to z but vowels
- regexp: named group: /(?<word>\w)\k<word>/ #repeat same words
- regexp: named group: /(?<hour>\d\d)/;"Hour is #{hour} #it also can refer after as param
- regexp: sub can get a hash as the replacement param
- regexp: 'a\b\b'.gsub(/\\/, '\&\&') # => "a\\b\\c"
- method: pass all params: def initialize(*); super; end
- method argument with splat: method_one(*[1,2], 3, *(4..8))
Web Site idea
- 同じテーマでの投稿をまとめたサイト
- ユーザによる投稿・評価
- 評価に応じて報酬
- あるいは記事をPDFとかにして販売
- 例えばRubyのブロックについての投稿
Monday, August 18, 2008
Programming Ruby 3rd
- Hash new idiom: { cell: 'string', clarinet: 'woodwind'}
- require_relative
- be capable Comparable: def <=>(other)
- be capable Enumerable: def each
- unit test
- parameters to a block are always local to a block
- [1,2,3].each {|value; square| square} #square is local
- inject(:+)
- external iterator: [1,2,3].to_enum.next
- enumerator makes objects enumerable
- enumerator stops loop
- -> { puts 'hello'}, -> arg, *ary, &block { |e| ... }
- 3 + 4.im
- string encoding
- Song = Struct.new(:title, :name, :length); Song.new('hello', 'John', 3.14)
Sunday, August 17, 2008
Ruby Accessor
1 #!/usr/local/bin/ruby
2 # encoding: utf-8
3 class Module
4 private
5 def attr_r(*arg)
6 arg.each do |key|
7 class_eval <<-EOS
8 def #{key}
9 @#{key}
10 end
11 EOS
12 end
13 end
14 end
15
16 class Book
17 attr_r :isbn, :price
18 def initialize(isbn, price)
19 @isbn, @price = isbn, Float(price)
20 end
21 end
22
23 b = Book.new(123, '10.45')
24 p b.isbn
25 p b.price
26 # >> 123
27 # >> 10.45
1 #!/usr/local/bin/ruby
2 # encoding: utf-8
3 class Module
4 private
5 def attr_r(*arg)
6 arg.each do |key|
7 define_method("#{key}") do
8 eval "@#{key}"
9 end
10 end
11 end
12 end
13
14 class Book
15 attr_r :isbn, :price
16 def initialize(isbn, price)
17 @isbn, @price = isbn, Float(price)
18 end
19 end
20
21 b = Book.new(123, '10.45')
22 p b.isbn
23 p b.price
24 # >> 123
25 # >> 10.45
Wednesday, August 13, 2008
Brooke Waggoner
Tuesday, August 12, 2008
Rubyと私
Sunday, August 10, 2008
eval
1 #!/usr/local/bin/ruby
2 # encoding: utf-8
3 class Array
4 def yield
5 yield self
6 end
7 def ival(s)
8 self.send(s)
9 end
10 end
11
12 [1,2,3].yield do |s|
13 puts s.reverse!
14 end
15
16 [1,2,3].instance_eval do
17 puts self.reverse!
18 end
19
20 a = [1,2,3]
21 a.ival "reverse!"
22 p a