我想重写这段话:

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.chipsapi入口点。
第二个片段更简洁,块内没有可更改的空间。
如何将game_id值从game_id方法隐式传递到Chips.fix_game对象?

最佳答案

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

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

关于ruby - 传递变量以隐式地在Ruby中阻止,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27035272/

10-11 23:14
查看更多