在Ruby / Rails中PHP的print_r是否相同?

时间:2009-01-29 12:36:09

标签: ruby-on-rails ruby

在PHP中你可以这样做:

print_r($var)vardump($var)

打印有关变量的“人类可读”信息。

Ruby / Rails中是否有等效的函数/助手?

8 个答案:

答案 0 :(得分:33)

在Rails模板中,您可以执行

<%= debug an_object %>

它会做很好的HTML PRE输出。

答案 1 :(得分:15)

尝试使用pp。 您需要在脚本中要求它(或者如果您的.irbc尚未执行此操作,则需要在irb中):

require 'pp'

然后你可以'PrettyPrint'这样一个对象:

pp object

答案 2 :(得分:10)

您可以简单地执行

,而不是要求'pp'和使用pp
p object

经过测试的例子

require 'pp'

class A
  def initialize
    @a = 'somevar'
    @b = [1,2,3]
    @c = {'var' => 'val'}
  end
end

a = A.new
pp a # Gives -> #<A:0x2c6d048 @a="somevar", @b=[1, 2, 3], @c={"var"=>"val"}>
p a # Gives -> #<A:0x2c6d048 @a="somevar", @b=[1, 2, 3], @c={"var"=>"val"}>. No need to require 'pp'

答案 3 :(得分:6)

方法inspect有帮助。有时在对象上调用to_s方法会有所帮助(to_s返回对象的字符串表示形式)。您还可以查询methodslocal_variablesclass_variablesinstance_variablesconstantsglobal_variables

p ['Hello',"G'day",'Bonjour','Hola'].inspect
# >> "[\"Hello\", \"G'day\", \"Bonjour\", \"Hola\"]"

p ['Hello',"G'day",'Bonjour','Hola'].to_s
# >> "HelloG'dayBonjourHola"

p Array.new.methods
# >> ["select", "[]=", "inspect", "compact"...]

monkey = 'baboon'
p local_variables
# >> ["monkey"]

class Something
  def initialize
    @x, @y = 'foo', 'bar'
    @@class_variable = 'gorilla'
  end
end

p Something.class_variables
# >> ["@@class_variable"]

s = Something.new
p s.instance_variables
# >> ["@x", "@y"]

p IO.constants
# >> ["TRUNC", "SEEK_END", "LOCK_SH"...]

p global_variables
# >> ["$-d", "$\"", "$$", "$<", "$_", "$-K"...]

答案 4 :(得分:5)

我知道这是一篇旧帖子,但这是Google在搜索“Ruby等效的PHP print_r”时弹出的第一件事。我在命令行模式下使用Ruby,并且确实没有非常好的等价物。 “pp”对于相当简单的结构是可以的,但是一旦你开始在更多数组中的哈希中的数组中嵌套哈希,它就变得非常快。由于我没有找到print_r的良好模拟,我自己写了一个。这对我的目的来说已经足够了,不会过于复杂,我想我会分享它以挽救其他人一些头疼的问题。将输出与real PHP print_r

进行比较
def print_r(inHash, *indent)
    @indent = indent.join
    if (inHash.class.to_s == "Hash") then
        print "Hash\n#{@indent}(\n"
        inHash.each { |key, value|
            if (value.class.to_s =~ /Hash/) || (value.class.to_s =~ /Array/) then
                print "#{@indent}    [#{key}] => "
                self.print_r(value, "#{@indent}        ")
            else
                puts "#{@indent}    [#{key}] => #{value}"
            end
        }
        puts "#{@indent})\n"
    elsif (inHash.class.to_s == "Array") then
        print "Array\n#{@indent}(\n"
        inHash.each_with_index { |value,index|
            if (value.class.to_s == "Hash") || (value.class.to_s == "Array") then
                print "#{@indent}    [#{index}] => "
                self.print_r(value, "#{@indent}        ")
            else
                puts "#{@indent}    [#{index}] => #{value}"
            end
        }
        puts "#{@indent})\n"
    end
    #   Pop last indent off
    8.times {@indent.chop!}
end

这是一个例子(故意弄乱,以显示PHP print_r为何如此美好):

    carTools =  [ "Socket Set", "Combination Wrenches", "Oil Filter puller", "Brake Compressor" ]
    houseTools =[ "Circular Saw", "Miter Saw", "Drill" ]
    garageItems = Hash["Car1" => "Ford Mustang", "Car2" => "Honda Civic", "Bike1" => "IronHorse"]
    garageItems["Tools"] = Hash["Car Tools" => carTools, "House Tools" => houseTools]
    constructionSupplies = Hash["Plywood" => ["3/4\" T&G Plywood Sheets", "1/2\" Plywood Sheets"],
                                "Boards" => ["2x4s", "2x6s", "Engineered I-Joists"],
                                "Drywall" => ["4x8 1/2\" Sheetrock", "Mesh tape", "Paper tape", "Joint compount"]]
    carParts = Hash["Mustang" => ["Clutch", "Transmission", "3.55 Ring & Pinion Gears", "Differential", "30# Injectors", "Pro-M 77mm MAF"]]
    garageItems["Supplies"] = ["Oil", "WD40", constructionSupplies, carParts, "Brake Fluid"]
    print_r(garageItems)

print_r的输出(实际上是人类可以理解的):

    Hash
    (
        [Car1] => Ford Mustang
        [Car2] => Honda Civic
        [Bike1] => IronHorse
        [Tools] => Hash
            (
                [Car Tools] => Array
                    (
                        [0] => Socket Set
                        [1] => Combination Wrenches
                        [2] => Oil Filter puller
                        [3] => Brake Compressor
                    )
                [House Tools] => Array
                    (
                        [0] => Circular Saw
                        [1] => Miter Saw
                        [2] => Drill
                    )
            )
        [Supplies] => Array
            (
                [0] => Oil
                [1] => WD40
                [2] => Hash
                    (
                        [Plywood] => Array
                            (
                                [0] => 3/4" T&G Plywood Sheets
                                [1] => 1/2" Plywood Sheets
                            )
                        [Boards] => Array
                            (
                                [0] => 2x4s
                                [1] => 2x6s
                                [2] => Engineered I-Joists
                            )
                        [Drywall] => Array
                            (
                                [0] => 4x8 1/2" Sheetrock
                                [1] => Mesh tape
                                [2] => Paper tape
                                [3] => Joint compount
                            )
                    )
                [3] => Hash
                    (
                        [Mustang] => Array
                            (
                                [0] => Clutch
                                [1] => Transmission
                                [2] => 3.55 Ring & Pinion Gears
                                [3] => Differential
                                [4] => 30# Injectors
                                [5] => Pro-M 77mm MAF
                            )
                    )
                [4] => Brake Fluid
            )
    )

答案 5 :(得分:2)

查看调试rails的指南: http://guides.rubyonrails.com/debugging_rails_applications.html

提示: 脚本/控制台非常适合在您的应用程序环境中尝试 脚本/服务器--debugger在启用调试器的情况下启动服务器,然后您可以在代码中使用'debug'来打破交互式shell

答案 6 :(得分:1)

我非常依赖的一种方法是:

logger.debug "OBJECT: #{an_object.to_yaml}"

易于阅读,虽然对于大型物体来说可能会有点笨拙。

答案 7 :(得分:0)

猜猜我迟到了,但是logger.info [debug | warning]怎么样?从控制器和模型中使用它。它将显示在您的日志文件中(开发模式下的development.log);和上面提到的<%= debug("str: " + str) %>视图。

这些不是您问题的确切答案,但您也可以使用脚本/控制台将rails应用程序加载到交互式会话中。

最后,您可以将调试器放在rails应用程序的一行中,当您的应用程序执行此行时,浏览器将“挂起”,您将能够从放置调试器的确切行进入调试会话源代码。