隐式地将变量传递给Ruby中的块

时间:2014-11-20 08:50:48

标签: ruby

我想改写那段代码:

Chips.fix_game(324565) do |game_id|
  player1.chips.gain(game_id, 200) # chips qty
  player2.chips.lose(game_id, 200)
end

这样:

Chips.fix_game(324565) do
  player1.chips.gain(200)
  player2.chips.lose(200)
end

以某种方式将game_id传递给player1.chips API入口点。

第二个片段更简洁,并且在块内没有可以更改game_id的空间。

您如何将game_id方法的Chips.fix_game值隐含地传递给player1.chips对象?

1 个答案:

答案 0 :(得分:0)

Chips可以提供使用current_game_id设置的fix_game,例如:

class Chips
  @@current_game_id = nil

  def self.current_game_id
    @@current_game_id
  end

  def self.fix_game(game_id)
    previous_game_id = current_game_id
    @@current_game_id = game_id
    yield
  ensure
    @@current_game_id = previous_game_id
  end
end

class Player
  def gain(amount)
    puts "gaining #{amount} chips in game #{Chips.current_game_id}"
  end
end

player = Player.new

Chips.fix_game(1) do
  player.gain(100)
end
#=> "gaining 100 chips in game 1"

Chips.fix_game(2) do
  player.gain(200)
end
#=> "gaining 200 chips in game 2"

yield允许嵌套块后恢复上一个游戏ID:

Chips.current_game_id     #=> nil
Chips.fix_game(1) do
  Chips.current_game_id   #=> 1
  Chips.fix_game(2) do
    Chips.current_game_id #=> 2
  end
  Chips.current_game_id   #=> 1
end
Chips.current_game_id     #=> nil

虽然这看起来很方便,但全局状态可能导致难以调试的问题。小心。