我的目标是尝试一种不寻常但有趣的方法来调用块。我来到那个代码:
class Chips
def self.configure player_class, player_id_method, player_api_method
player_class.send :define_method, player_api_method do
Chips::Player.new(self.send player_id_method)
end
end
def self.fix_game game_id
@@game_results = {game_id: game_id, players: []}
yield
puts @@game_results.inspect
end
class Player
def initialize player_id
@player_id= player_id
end
def gain chips
Chips.send :fix_player, @player_id, chips.abs
end
def lose chips
Chips.send :fix_player, @player_id, -chips.abs
end
end
def self.fix_player player_id, chips
@@game_results[:players]<< {player_id: player_id, chips: chips}
end
private_class_method :fix_player
end
class User
attr_reader :email
def initialize email
@email = email
end
end
Chips.configure User, :email, :chips
p1= User.new 'david@gmail.com'
p2= User.new 'simon@gmail.com'
# p1.chips and p2.chips should have access to the value
# currently accessible by @@game_results reference
Chips.fix_game 3333 do
p1.chips.gain 300
p2.chips.lose 300
end
...输出{:game_id=>3333, :players=>[{:player_id=>"david@gmail.com", :chips=>300}, {:player_id=>"simon@gmail.com", :chips=>-300}]}
我想避免使用类变量。
PS
问题创建表格不允许我提交这个问题,直到我添加更多的单词,这实际上是对强大的门卫的祈祷。我给你带来了更多的字节,TMD。我遵守。