## 2014年10月22日 星期三

### [ Ruby Gossip ] Basic : 方法 - def 定義方法

Source From Here
Preface

1. def gcd(m, n)
2.     n == 0 ? m : gcd(n, m % n)
3. end
4. puts gcd(2030) # 顯示 10

def 定義方法

1. obj = Object.new
2. def obj.gcd(m, n)
3.     n == 0 ? m : gcd(n, m % n)
4. end
5. puts obj.gcd(2030) # 顯示 10

1. class Object
2.     # 以下定義了gcd實例方法
3.     def gcd(m, n)
4.         n == 0 ? m : gcd(n, m % n)
5.     end
6.     private :gcd
7. end

1. # encoding: Big5
2. def sum(a, b, c = 0)
3.     a + b + c
4. end
5.
6. puts sum(102030)  # 顯示 60
7. puts sum(1020)      # 顯示 30

1. def sum(*numbers)
2.     total = 0
3.     numbers.each do |number|
4.         total += number
5.     end
6.     total
7. end
8.
9. puts sum(12)       # 顯示 3
10. puts sum(123)    # 顯示 6
11. puts sum(1234) # 顯示 10

1. def sum(a, b, c)
2.     a + b + c
3. end
4.
5. numbers = [123]
6. puts sum(*numbers)   # 顯示 6

1. def some
2.     [123]
3. end
4. x, y, z = some
5. puts "#{x}, #{y}, #{z}"   # 顯示 123

>> def some(a, b = 10, c, d)
>> p a, b, c, d
>> end
=> nil
>> some(1, 2, 3, 4)
1
2
3
4

=> [1, 2, 3, 4]
>> some(1, 2, 3)
1
10
2
3

=> [1, 10, 2, 3]

1. def selection(number)
2.     # Search index with minimum value among nums[m..-1]
3.     def min(nums, m, j)
4.         if j == nums.length
5.             m
6.         elsif nums[j] < nums[m]
7.             min(nums, j, j+1)
8.         else
9.             min(nums, m, j+1)
10.         end
11.     end
12.
13.     for i in 0..(number.length - 1)
14.         m = min(number, i, i+1)
15.         if m != i
16.             number[i], number[m] = number[m], number[i]
17.         end
18.     end
19. end
20.
21. number = [152397]
22. printf("Before sort: %s\n", number)
23. selection(number)
24. printf("After sort: %s\n", number)

Supplement
[ DS with Java ] Section 4.1 : Selection Sort

### [ Python 常見問題 ] python generator “send” function purpose?

Source From  Here   Question   Can someone give me an example of why the "send" function associated with Python generator function...