rubyメモ

文字列とシンボルの違い

"name".class # =>String
"name".intern.class # => Symbol
:name.object_id == "name".object_id # => false
:name.object_id == "name".intern.object_id # => true

配列

[1,2,3]
[:num, 10]
%w( a b c) # ['a', 'b', 'c']と同じ

条件式

if/unless/while で偽と判断されるのは nil と false だけ

ブロックと yield

単純にブロックを実行

def anyBlock
  yield
end

anyBlock { p 'test' }

ブロックを引数で渡す

def anyBlock(&block)
  block.call
end

anyBlock {p 'test' }

ブロックを引数で渡す(yieldで実行)

def anyBlock(&block)
  yield
end

anyBlock {p 'test' }

ブロック引数?

sum = Proc.new{|a,b| a + b}
sum.call(10,15)

Arrayクラス

[1,2,3].each{|i| p i}
[1,2,3].map{|i| i.to_s} #=> ["1", "2", "3"]
 (1..10).select{|i| i % 2 == 0} #=> [2, 4, 6, 8, 10]
(1...10).select{|i| i % 2 == 0} #=>[2, 4, 6, 8]
class Array
  def each
    size.times {|i| yield(self[i])}
  end

  def collect
    each {|e| converted << yield(e)}
    return converted
  end

  def select
    selected = []
    each {|e| selected << e if yield(e) }
    return selected
  end
end