Ruby Tricks
                                            
                                                
                                                
                                                
                                                
                                                
                                                 11304 단어  Ruby
                    
 **에서 매개 변수로 Hash 수신
def my_method(a, *b, **c)
  return a, b, c
end
my_method(1)
# => [1, [], {}]
my_method(1, 2, 3, 4)
# => [1, [2, 3, 4], {}]
my_method(1, 2, 3, 4, a: 1, b: 2)
# => [1, [2, 3, 4], {:a=>1, :b=>2}]
Single Object 및 Arry 작업을 동일하게 처리
stuff = 1
stuff_arr = [1, 2, 3]
[stuff].map { |s| s + 1 }    
# = Array(stuff).map { |s| s + 1 }
[*stuff_arr].map { |s| s + 1 }    
# = stuff_arr.map { |s| s + 1 }    
# = Array(stuff_arr).map { |s| s + 1 }
|||=(@total이 비어 있을 때 실행)
첫 번째는 시간이 필요하고, 두 번째는 시간이 걸리지 않는다.
require 'benchmark'
def total(val)
  @total ||= (1..val).to_a.inject(:+)
end
result = Benchmark.realtime do
    total(100000000)
end
puts "1: #{result.round(2)}s"
result = Benchmark.realtime do
    total(100000000)
end
puts "2: #{result.round(2)}s"
자모
('a'..'z').to_a # [*'a'..'z']
# => ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
(1..10).to_a # [*1..10]
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Tap
class User
  attr_accessor :a, :b, :c
end
def my_method
  o = User.new
  o.a = 1
  o.b = 2
  o.c = 3
  o
end
# より読みやすくする
def my_method_readble
  User.new.tap do |o|
    o.a = 1
    o.b = 2
    o.c = 3
  end
end
객체 복사
base = [1, 2, 3]
copy = base
copy.reverse!
p "--- = ---"
p copy
p base
p copy.equal?(base)
base = [1, 2, 3]
copy = base.dup
copy.reverse!
p "--- dup ---"
p copy
p base
p copy.equal?(base)
defxxx (& yy) 블록 매개 변수
yield
호출 블록
def block
  yield
end
block do
  p "This is block!"
end
# "This is block!"
Proc
블록을 대상화한 후 콜에서 호출할 수 있습니다
Proc.new와 lambda는 거의 동의입니다.
프로세스:실행
lambda: ArgumentError
Proce:call 컨텍스트 반환(최상위 수준인 경우 Local JumpError)
lambda: 블록에서 처리 종료
proc = Proc.new do
  p "This is proc!"
end
proc.call
# "This is proc!"
lambda = lambda {p "This is lambda!"}
# lambda = -> {p "This is lambda!"}
lambda.call
# "This is lambda!"
블록 매개변수
블록 매개 변수 명확히 받아들이기 &
추가 & 를 통해 매개 변수가 프로세스 대상으로 전송될 때 프로세스 대상으로 변환합니다
def test1(&block)
    yield
end
test1 do
  p "This is block1!"
end
# "This is block1!"
def test2
    yield
end
test2 do
  p "This is block2!"
end
# "This is block2!"
                Reference
이 문제에 관하여(Ruby Tricks), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/sunoko/items/78209dd0e54fc0024f6e텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)