Difference between block and &block in Ruby

前端 未结 3 1755
执笔经年
执笔经年 2021-01-30 01:47

Why sometimes I should use block and other times &block inside functions that accept blocks?

3条回答
  •  清歌不尽
    2021-01-30 02:23

    block is just a local variable, &block is a reference to the block passed to the method.

    def foo(block = nil)
      p block
    end
    
    foo # => nil
    foo("test") # => test
    foo { puts "this block will not be called" } # => nil
    
    def foo(&block)
      p block
    end
    
    foo # => nil
    foo("test") # => ArgumentError: wrong number of arguments (1 for 0)
    foo { puts "This block won't get called, but you'll se it referenced as a proc." }
    # => #
    

    You can also use &block when calling methods to pass a proc as a block to a method, so that you can use procs just as you use blocks.

    my_proc = proc {|i| i.upcase }
    
    p ["foo", "bar", "baz"].map(&my_proc)
    # => ["FOO", "BAR", "BAZ"]
    
    p ["foo", "bar", "baz"].map(my_proc)
    # => ArgumentError: wrong number of arguments (1 for 0)
    

    The variable name block doesn't mean anything special. You can use &strawberries if you like, the ampersand is the key here.

    You might find this article helpful.

提交回复
热议问题