Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Rubyとblock

 Rubyとblock

murajun1978

February 19, 2014
Tweet

More Decks by murajun1978

Other Decks in Programming

Transcript

  1. yield def foo yield if block_given? end foo do puts

    "Hello!" end #=> Hello! ! foo #=>
  2. proc def foo &proc proc.call end proc = Proc.new do

    puts "Hello!" end foo &proc #=> Hello!
  3. proc def foo name, &proc proc.call(name) end proc = Proc.new

    do |name| puts “Hello, #{name}!” end foo “Ruby”, &proc #=> Hello, Ruby!
  4. lambda def foo &lambda lambda.call end lambda = -> {puts

    “Hello!”} foo &lambda #=> Hello!
  5. proc ͱ lambda def foo block block.call 1, 2 end

    foo proc { |x, y, z| p x #=> 1 p y #=> 2 p z # => nil } def foo block block.call 1, 2 end foo lambda { |x, y, z| p x p y p z } # ArgumentError
  6. Rails model class User < ActiveRecord::Base def admin? end end

    admin = [] User.all.each do |user| admin << user if user.admin? end User.select {|user| user.admin?} User.select(&:admin?)
  7. Rails model scope class User < ActiveRecord::Base AUTHORITY_ADMIN = “admin”

    scope :admin, -> { where(authority: AUTHORITY_ADMIN) } ! def admin? end end