不能打印一个对象 - Can't print an object

- 此内容更新于:2016-02-02
主题:

我打印一个对象。我来自Python的面向对象方面Ruby并不困难,但有些力学很难学习。从来没有一个问题关于印刷一个对象通过重写to_s方法在python中,但,我不能。我让你看下面的代码。(我也试图维持rdoc的学生在这个小项目对我项目的配偶)引擎类我想打印@gridgenRandGrid方法但它只打印0..9。谢谢。

原文:

I'm trying so hard to print an object. I come from Python so the OO aspect of Ruby isn't so hard but some mechanics are hard to learn. Never had a problem about printing an object by overriding the to_s method in python but there, i can't. I let you watch the following code. (i'm also trying to maintain rdoc in this little student project for my project's mates)

gem "rmagick"
gem "rdoc"
require "rmagick"
require "rdoc/rdoc"
include Magick
##
# This class represents the complete +Game+
class Game
    # Debugging accessor
    attr_accessor :engine

    ##
    # Creates a new instance of the game
    def initialize()
        @engine = Engine.new
    end

    ##
    # Starts the engine
    def start()
        @engine.genRandomGrid()
    end
end
##
# This class represents the +Controller+ from +MVC+
class Engine
    # Debugging accessor
    attr_accessor :grid

    ##
    # Initiates the needed instance's variables
    def initialize(x = 10)
        @grid = Grid.new(x)
    end

    ##
    # Generates a x * x grid of +Cell+ with false value/state
    def genNewGrid(x = 10)
        @grid = Grid.new(x)
    end

    ##
    # Fills the current grid with random value
    def genRandomGrid()
        @grid.randomGrid()
        p @grid
    end

    ##
    # Fills the current grid with picture's values
    def genPictureGrid(path)
        @grid.picture(path)
    end
end

##
# This class represents a +Grid+
class Grid 
    # Debugging accessor
    attr_accessor :maxLen #Longueur/Largeur
    # Debugging accessor
    attr_accessor :matrix #2 listes. Voir object Cell
    # Debugging accessor
    attr_accessor :xIndices #Les indices au dessus des abscisses 
    # Debugging accessor
    attr_accessor :yIndices #Les indices à gauche des ordonnées

    ##
    # Initializes +@grid+, +@xIndices+ and +@yIndices+ with 2D Array
    def initialize(x = 10)
        @maxLen = x
        @matrix = Array.new(x){Array.new(x){Cell.new(false, false)}}
        @xIndices = Array.new(x){Array.new}
        @yIndices = Array.new(x){Array.new}
    end

    ##
    # Turns to false a true cell state and to true a false cell state
    def changeCellState(x, y)
        @matrix[x][y].changeState
    end

    ##
    # Returns the @maxLen if needed
    def getLength()
        return @maxLen
    end

    ##
    # Generates "randomly" the value of each grid's cell
    def randomGrid()
        @matrix.each do |j|
            j.each do |x|
                rand_value = Random.srand(Random.new_seed)
                if ( rand_value % 2) == 0
                    x.setValue(true)
                else
                    x.setValue(false)
                end
            end
        end
        evalIndices()
        # NB : Class is array
        p #{@matrix}
    end

    ##
    # TODO : Generates a grid from a picture
    def picture()

    end

    ##
    # Fills +@xIndices+ and +@yIndices+ with right values
    def evalIndices()
        _row = 0
        _in = false
        _nb = 0
        @matrix.each do |j|
            _in = false
            _nb = 0
            j.each do |x|
                if x.getValue
                    _in = true
                    _nb += 1
                elsif _in
                    @xIndices[_row].push(_nb)
                    _in = false
                    _nb = 0
                end
            end
            if _in
                @xIndices[_row].push(_nb)
                _in = false
                _nb = 0
            end
            _row += 1
        end

        for j in 0..@maxLen-1
            _in = false
            _nb = 0
            for i in 0..@maxLen-1
                if @matrix[i][j].getValue 
                    _in = true
                    _nb += 1
                elsif _in
                    @yIndices[j].push(_nb)
                    _in = false
                    _nb = 0
                end
            end
            if _in
                @yIndices[j].push(_nb)
                _in = false
                _nb = 0
            end
        end
    end

    def to_s
        ret = ""
        @matrix.each do |j|
            j.each do |cell|
                ret += cell.getValue
            end
            ret += "\n"
        end
        return ret
    end
end


##
#  This class represents a +Cell+
class Cell
    # Debugging accessor
    attr_accessor :state #Etat graphique (GUI)
    # Debugging accessor
    attr_accessor :value #Valeur réelle (MOTEUR)

    ##
    # Initializes the +@state+ and +@value+ with parameters
    def initialize(state, value)
        @state = state
        @value = value
    end

    ##
    # Makes the +Cell+ object printable
    def to_s
        if @value
            "[X]"
        else
            "[ ]"
        end
    end

    ##
    # Boolean access method
    def changeState()
        if @state == true
            @state = false
        else
            @state = true
        end
    end

    ##
    # Access method
    def setValue(value)
        @value = value
    end

    ##
    # Access method
    def getState()
        return @state
    end

    ##
    # Access method
    def getValue()
        return @value
    end

    ##
    # Verifies if +@state+ and +@value+ are the same
    def right?
        return @state && @value
    end
end


game = Game.new
game.start()

In the Engine Class i'm trying to print @grid in the genRandGrid method but it only prints 0..9.

Thx.

网友:你有试过吗?

(原文:Have you tried p?)

楼主:p@grid给我相同的结果。我有一些奇怪的事情。有时我有“指针”的对象和内容,其他时间0..9范围,其他时间错误。今天我真的开始ruby这有点令人沮丧,无法做事情我可以做很容易在Python中。我在对象中创建对象也许我用神谕的,不能以这种方式做Rubyonic道:)。

(原文:p @grid gives me the same result. I have some strange things. Sometime i have the "pointer" of the object and the content, other time the 0..9 range, other time errors. I really began ruby today so it's a bit frustrating to not be able to do things i can do easily in Python. I create objects in objects maybe i do it in a Pythonic way that can't be done in this way in Rubyonic way :).)

网友:只是看看你的代码和看到一些循环!在Ruby中,你应该使用或其衍生品如果你能之一:)

(原文:Just glancing through your code and saw some for loops! In Ruby you should use each or one of its derivatives if you can:))

楼主:我想练习你告诉我些什么。每个方法,我不认为问题来自于声明或。每个方法因为我试图取代它,它仍然相同的(错误)。我编辑的代码。

(原文:I'm trying to practice what you told me about .each method and i don't think the problem comes from the for statement or .each method because i tried to replace it and it still the same thing (with more errors). I'll edit the code with the new one.)

解决方案:
变量的类型是什么,当你打印它吗?结果返回的类型,并不是对象。你可以打印类,以确保和修复代码:您共享的代码需要一些改进。Ruby是一个非常宽容的语言,现在,没有很好的管理类型的代码。此外,我不认为惯用Ruby是必要的为了实现你的目标,但是代码可以简化很多,这将简化推理的几个方面,包括类型。
原文:

What is the type of the @grid variable when you print it?

It turns out it is the type returned by @grid.random, and it is not a Grid object. You may print the class to ensure that, and fix the code:

puts @grid.class

The code you shared needs quite some improvements. Ruby is a very permissive language, and right now, the code does not manage well the types. Also, I don't think idiomatic Ruby is necessary to achieve your goals, but the code can be simplified quite a lot, which would simplify reasoning about several aspects, including types.

楼主:我想evalIndices方法转换成Ruby的way_to_do但我怎么能读一个数组的数组首先xy然后?最后,我想获得一个可打印矩阵包含对象(我的细胞对象可打印)。@grid的类型。类是“数组”。

(原文:I'm trying to convert evalIndices method into Ruby's way_to_do but how can i read an Array of Arrays first by y then by x ? Finally, i just wanna get a printable matrix that contains objects (my Cell object is printable). The type of @grid.class is 'Array'.)

楼主:如何?我理解为什么你告诉我。我网格对象的数组,而不是…我怎么能返回数组的对象,而不是一个数组?我真不敢相信这是错误……initialize方法不返回一个数组但nil值对吧?(如在pythonNoneObject?)。我很惊讶和无聊的语言^^。我不知道如何解决这个问题,我开始这门语言几个小时……

(原文:How ? I just understood why you told me that. I've an Array instead of Grid object ... How can i return the object instead of an Array of arrays ? I can't believe that it's the mistake ... The initialize method doesn't return an array but nil value right ? (like NoneObject in python?). I'm amazed and bored by this language ^^. I don't know how to fix that, i began this language for a few hours ...)

楼主:我编辑代码,谢谢的帮助。这一个我也仍然不能打印to_s方法在这两个对象(#单元对象返回[X]或[]如果@value是真的还是假的)和#网格对象返回一个字符串用细胞。仍然不能打印出来…

(原文:I edited the code, thank's for helping. With this one i'm still not able to print also i have to_s methods in both objects (#Cell object return [X] or [ ] if @value is at true or false) and #Grid object returns a string made with Cells. Still not able to print it ...)

网友:方法在Ruby中返回的值上执行语句。这种机制是隐式的。是一个例外,并返回。

(原文:Methods in Ruby return the value of the last executed statement. This mechanism is implicit. #initialize is an exception and returns self.)