kitaro-tn
12/10/2016 - 2:19 AM

Rubyやってます、(`・ω・´)キリッ という為に押さえときたいテクニック ref: http://qiita.com/kitaro_tn/items/6372e3efad558f18b3b5

Rubyやってます、(`・ω・´)キリッ という為に押さえときたいテクニック ref: https://qiita.com/kitaro_tn/items/6372e3efad558f18b3b5

class HttpRest

  def get(url, params, opts)
  end

  def post(url, params, opts)
  end

  def put(url, params, opts)
  end

  def delete(url, params, opts)
  end

end

class Client

  attr_reader :response

  def initialize(action, url, params, opts)
    @response = HttpRest.new.send(action.to_sym, url, params, opts)
  end

end
# coding: utf-8

class Calc

  attr_reader :num

  def initialize(num)
    @num = num
  end

  def plus
    self.tap { @num += 1 }
  end

  def minus
    self.tap { @num -= 1 }
  end

end

calc = Calc.new(1)
calc.plus.plus.plus.minus.plus.minus
p calc.num
# coding: utf-8

class Calc

  attr_reader :num

  def initialize(num)
    @num = num
  end

  def plus
    @num += 1
    self
  end

  def minus
    @num -= 1
    self
  end

end

calc = Calc.new(1)
calc.plus.plus.plus.minus.plus.minus
p calc.num # 3
def hoge(name)
  return "No name" if name.nil?
  @name = name
end
def calc(num)
  num ||= 0
  num += 1
end
Proc.new { |x, y| }.call(1) # 1
lambda { |x, y| }.call(1) # ArgumentError
# &blockを引数として渡すと、メソッド内部でProcオブジェクトを呼び出すことが出来る
def agree(&block)
  printf "Hello,"
  block.call if block_given?
end

# yieldを使うことで、上記を省略した書き方ができる
def agree2
  printf "Hey!,"
  yield if block_given? # blockが与えられたかを判定するので、必ず入れておいたほうがいい
end

agree { p "Tom" }
agree2 { p "Sam" }

# Hello,"Tom"
# Hey!,"Sam"
@num = 0
counter = Proc.new { @num += 1 }
counter.call # 1
counter.call # 2
class Sample

  # クラスメソッド
  def self.hoge    
  end

  def initialize
    @foo = "foo" # インスタンス変数
  end

  # インスタンスメソッド
  def foo
    @foo 
  end

end