Skip to content

Instantly share code, notes, and snippets.

@tanish-kr
Last active March 30, 2018 03:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanish-kr/8c163ffa9cfdb5560686e06bcdb26e97 to your computer and use it in GitHub Desktop.
Save tanish-kr/8c163ffa9cfdb5560686e06bcdb26e97 to your computer and use it in GitHub Desktop.
Rubyやってます、(`・ω・´)キリッ という為に押さえときたいテクニック ref: https://qiita.com/kitaro_tn/items/6372e3efad558f18b3b5
class Sample
# クラスメソッド
def self.hoge
end
def initialize
@foo = "foo" # インスタンス変数
end
# インスタンスメソッド
def foo
@foo
end
end
@num = 0
counter = Proc.new { @num += 1 }
counter.call # 1
counter.call # 2
# &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"
Proc.new { |x, y| }.call(1) # 1
lambda { |x, y| }.call(1) # ArgumentError
def calc(num)
num ||= 0
num += 1
end
def hoge(name)
return "No name" if name.nil?
@name = name
end
# 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
# 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
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment