【问题标题】:How do I print Ruby objects as strings?如何将 Ruby 对象打印为字符串?
【发布时间】:2016-03-31 02:55:15
【问题描述】:

我有一个类Board,它包含来自另一个类Cell 的对象,我想将它们打印为板。我为每个单元格随机分配了'x''o' 的值,我希望它打印'x''o' 的二维数组。 这是我的代码:

class Cell
  attr_accessor :cell
  def initialize
    @cell = ['x', 'o'].sample
  end
end

class Board
  attr_reader :board
  attr_accessor :row
  def initialize
    @board = Array.new(9)
    @row = Array.new(9)
    @my_cell = ''
  end
  def create_row
    self.row.map! do |empty_space|
      empty_space == nil ? Cell.new : empty_space
    end
  end
  def create_board
    self.board.map! do |empty_space|
      empty_space == nil ? self.row : empty_space
    end
  end
  def to_s
    self.board
  end
end

new_board = Board.new
new_board.create_row
new_board.create_board
puts new_board.to_s

当我打印板时,它给了我一个单元格对象坐标的列表。我想不通。

【问题讨论】:

  • 对于特定的自定义输出,您可能希望使用某种循环来生成自定义的“漂亮板”。但是,对于快速调试,#inspect 可能很有用。例如:def to_s; self.board.inspect end
  • 格式很糟糕,您对self 的使用不一致。有时您使用它,有时您不使用它。

标签: arrays ruby object


【解决方案1】:

to_s 应该返回一个String,这就是为什么它首先被称为to_s。您从 to_s 返回 Array,而不是 String

【讨论】:

    【解决方案2】:

    试试 awesome_print。这很棒。它以非常易读的格式转储您的对象,例如:

     :014 > ap Major.first
      Major Load (4.2ms)  SELECT  "majors".* FROM "majors"  ORDER BY     "majors"."id" ASC LIMIT 1
     #<Major:0x007f8677e77c50> {
             :id => 9,
           :name => "Art",
     :profile_id => 85676,
     :school_code => 123,
     :created_at => Fri, 11 Dec 2015 21:22:25 UTC +00:00,
     :updated_at => Fri, 11 Dec 2015 21:22:25 UTC +00:00
    }
    

    您可以在 github 上找到它或将其添加到您的 Gemfile 中

    # Installing as Ruby gem
    $ gem install awesome_print
    
    # Cloning the repository
    $ git clone git://github.com/michaeldv/awesome_print.git
    

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 1970-01-01
      • 2023-03-11
      • 2021-12-13
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多