【问题标题】:Accessing instance variable array using IRB使用 IRB 访问实例变量数组
【发布时间】:2015-12-17 13:41:12
【问题描述】:

我是 Ruby 的新手,正在做一个运动队(最多 10 人)必须至少有 2 名男性和 2 名女性的练习。我创建了一个 Player 类,其中确定了玩家的性别,并创建了一个 Team 类,我将这些玩家添加到 @team 的实例变量数组中(在 Team 初始化时创建)。

我已将完整代码放在此请求的底部。

我希望有人可以在以下方面帮助我:

(1) 我在 IRB 中输入什么才能专门调用/操作 @team 实例变量数组(存储所有球员)。我希望稍后迭代数组或提取数组中的第一项(@team.first 不起作用)

(2) 我很难编写代码来确定@team 实例变量中是否至少有 2 名男性和女性玩家。我在 Team 类中提出的最佳代码如下 - 但它报告 @team 是 nilclass。

def gender_balance
   @team.select{|player| player.male == true }
end

我已经研究了互联网并尝试了各种组合以获得答案 - 没有成功。

下面是我输入的用于创建和添加球员到球队的 IRB 命令。下面是我的团队代码(其中包含评估其是否具有正确性别组合的方法)和玩家代码。

irb(main):001:0> team = Team.new
=> #<Team:0x007fd8f21df858 @team=[]>

irb(main):002:0> p1 = Player.new
=> #<Player:0x007fd8f21d7b08 @male=true>

irb(main):003:0> p1.female_player
=> false

irb(main):004:0> p2 = Player.new
=> #<Player:0x007fd8f21bff58 @male=true>

irb(main):005:0> team.add_player(p1)
=> [#<Player:0x007fd8f21d7b08 @male=false>]

irb(main):006:0> team.add_player(p2)
=> [#<Player:0x007fd8f21d7b08 @male=false>, #<Player:0x007fd8f21bff58 @male=true>]

这两条 IRB 行是我试图回忆@team 的内容但没有成功

irb(main):007:0> team
=> #<Team:0x007fd8f21df858 @team=[#<Player:0x007fd8f21d7b08 @male=false>, #<Player:0x007fd8f21bff58 @male=true>]>

irb(main):013:0> @team
=> nil

两个类的代码如下:

class Player
  def initialize
    @male = true
  end

  def female_player
    @male = false
  end

  def male_player
    @male
  end
end


class Team

  def initialize
    @team = []
  end

  def add_player player
    @team << player
  end

  def player_count
    @team.count
  end

  def valid_team?
    player_number_check
    gender_balance
  end

private
  def player_number_check
    player_count > 6 && player_count < 11
  end

 def gender_balance
   @team.select{|player| player.male == true }
 end
end

我对这段代码的 github 参考是:https://github.com/elinnet/object-calisthenics-beach-volleyball-edition.git

谢谢。

【问题讨论】:

    标签: ruby instance-variables irb


    【解决方案1】:

    您的Team 类没有用于获取@team 实例变量的属性。 因此,提取其值的唯一方法是使用instance_variable_get

    irb(main):029:0> team = Team.new
    => #<Team:0x007fff4323fd58 @team=[]>
    irb(main):030:0> team.instance_variable_get(:@team)
    => []
    

    请不要将instance_variable_get 用于实际生产代码;这是一种代码气味。但是为了检查 IRB 中的实例变量,没关系。

    您通常会在类定义中使用attr_accessor :team(读/写)或attr_reader :team(只读)来定义一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-08
      • 1970-01-01
      • 2012-07-16
      • 2016-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-05
      相关资源
      最近更新 更多