ruby-block

How to check block is called using rspec

那年仲夏 提交于 2021-01-28 00:29:09
问题 I want to check whether the block is called in my function using rspec. Below is my code: class SP def speak(options={},&block) puts "speak called" block.call() rescue ZeroDivisionError => e end end describe SP do it "testing speak functionality can receive a block" do sp = SP.new def test_func a = 1 end sp_mock = double(sp) expect(sp_mock).to receive(:speak).with(test_func) sp.speak(test_func) end end Below is my error: SP testing speak functionality can receive a block Failure/Error: block

How does the block form of Array#new work given “Array.new(10) { |e| e = e * 2 }”?

ⅰ亾dé卋堺 提交于 2020-01-11 14:00:14
问题 I am having trouble understanding the part inside the curly braces. Array.new(10) { |e| e = e * 2 } # => [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] I get that a new array with ten values is created, but what is the second half doing? 回答1: Let's go over this in details: nums = Array.new(10) This creates a new array with 10 elements. For each array element it passes control to the block specified by: { |e| e = e * 2 } The |e| represents the element's index. The index is the position in the array. This