Programming Ruby 2 nd読書ノート2
C05 Standard Types
1. String
2. Range
3. Regular Expression
C06 Method
1.可変パラメータ
2. Block
3.Hashパラメータ
4. Lambda
C07 Expressions
1. Overload operator
2.コマンドの実行
3.並列割付
4. Case
5. Variable Scope
while,for,if,utilなどは新しい役割ドメインをもたらしませんが,blockの使用は,新しい役割ドメインをもたらします.
1. String
print <<STRING1,<<STRING2
Concat
STRING1
enate
STRING2
produces:
Concat
enate
2. Range
a = 1..3 #a = 1,2,3
a = 1...3 # a = 1,2
(1..10) === 5 ! true
(1..10) === 15 ! false
(1..10) === 3.14159 ! true
('a'..'j') === 'c' ! true
('a'..'j') === 'z' ! false
class UV
include Comparable
attr :volume
def initialize(volume) # 0..9
@volume = volume
end
def inspect
'#' * @volume
end
# Support for ranges
def <=>(other)
self.volume <=> other.volume
end
def succ
raise(IndexError, "Volume too big") if @volume >= 9
VU.new(@volume.succ)
end
end
(1..10) === 15 -> false
(1..10) === 3.14159 -> true
('a'..'j') === 'c' -> true
('a'..'j') === 'z' -> false
3. Regular Expression
re = /(\d+):(\d+)/ # match a time hh:mm
md = re.match("Time: 12:34am")
md.class -> MatchData
md[0] # == $& -> "12:34"
md[1] # == $1 -> "12"
md[2] # == $2 -> "34"
md.pre_match # == $` -> "Time: "
md.post_match # == $' -> "am"
C06 Method
1.可変パラメータ
def varargs(arg1, *rest)
"Got #{arg1} and #{rest.join(', ')}"
end
puts(varargs("one", "two", "three"))
2. Block
def take_block(p1)
if block_given?
yield(p1)
else
p1
end
end
puts(take_block("no block"))
puts(take_block("no block"){|x| x.sub(/no /, '')})
class TaxCalculator
def initialize(name, &block)
@name = name
@block = block
end
def get_tax(amount)
"#{@name} on #{@amount} = #{@block.call(amount)}"
end
end
tc = TaxCalculator.new("Sales Tax"){|amt| amt * 0.075}
puts(tc.get_tax(100))
3.Hashパラメータ
def match_score(time, scores)
puts("Match score on #{time}")
scores.each do |name, score|
puts("#{name} -- #{score}")
end
end
match_score('2009-03-15',
'Zhibin' => 7,
'Henry' => 3,
'Keyu' => 2
)
4. Lambda
print('(t)imes or (p)lus')
times = gets
print('number:')
number = Integer(gets)
if times =~ /^t/
calc = lambda { |n| n * number }
else
calc = lambda { |n| n + number }
end
puts((1..10).collect(&calc).join(', '))
C07 Expressions
1. Overload operator
class Fixnum
alias old_plus +
def +(other)
old_plus(other).succ
end
end
puts(1+2)
2.コマンドの実行
puts(`date`)
puts($?)
puts(%x{echo 'hello world'})
puts($?)
puts(`./test.x`)
puts($?)
3.並列割付
b, (c, d), e = 1,2,3,4 -> b == 1, c == 2, d == nil, e == 3
b, (c, d), e = [1,2,3,4] -> b == 1, c == 2, d == nil, e == 3
b, (c, d), e = 1,[2,3],4 -> b == 1, c == 2, d == 3, e == 4
b, (c, d), e = 1,[2,3,4],5 -> b == 1, c == 2, d == 3, e == 5
b, (c,*d), e = 1,[2,3,4],5 -> b == 1, c == 2, d == [3, 4], e == 5
4. Case
def vowel_count(word)
count = 0
word.each_char do |c|
case c
when 'a'
count += 1
when 'e'
count += 1
when 'i'
count += 1
when 'o'
count += 1
when 'u'
count += 1
end
end
count
end
puts(vowel_count('I love u!'))
5. Variable Scope
while,for,if,utilなどは新しい役割ドメインをもたらしませんが,blockの使用は,新しい役割ドメインをもたらします.