在Ruby / Rails中,PHP的print_r是否等价?

时间:2021-05-06 23:30:45

In PHP you can do:

在PHP中,您可以这样做:

print_r($var) or vardump($var)

print_r(var)美元或vardump($ var)

which prints "human-readible" information about variable.

打印关于变量的“人易读”信息。

Is there equivalent functions / helpers for those in Ruby / Rails ?

Ruby / Rails中是否有相同的函数/助手?

8 个解决方案

#1


33  

In Rails templates you can do

在Rails模板中,您可以这样做。

<%= debug an_object %>

and it will do nice HTML PRE output.

它会做很好的HTML预输出。

#2


15  

Try using pp. You will need to require it in scripts (or in irb if your .irbc doesn't already do this):

尝试使用pp。您将需要在脚本中使用它(或者在irb中,如果您的。irbc还没有这样做的话):

require 'pp'

Then you can 'PrettyPrint' an object thus:

然后,你可以这样“美化”一个对象:

pp object

#3


10  

Instead of requiring 'pp' and using pp, you can simply do

不需要“pp”和使用pp,你可以做的很简单

p object

Tested example

测试的例子

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'

#4


6  

There's the method inspect which helps. Sometimes calling the to_s method on an object will help (to_s returns a string representation of the object). You can also query methods, local_variables, class_variables, instance_variables, constants and global_variables.

有一种方法可以帮上忙。有时调用对象上的to_s方法会有所帮助(to_s返回对象的字符串表示形式)。您还可以查询方法、local_variables、class_variables、instance_variables、constant和global_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"...]

#5


5  

I know this is an old post, but it is the first thing that Google pops up when searching for "Ruby equivalent of PHP print_r". I'm using Ruby in the command line mode, and there's really not a very good equivalent. "pp" is ok for fairly simple structures, but as soon as you start nesting hashes in arrays in hashes in more arrays, it turns into a jumble pretty fast. Since I haven't found a good emulation of print_r, I wrote one myself. It's good enough for my purposes, not overly complicated and I thought I'd share it to save other people some headache. Compare the output with the real PHP print_r

我知道这是一篇老文章,但这是谷歌在搜索“Ruby等价的PHP print_r”时首先出现的内容。我在命令行模式中使用Ruby,实际上并没有很好的对等。“pp”对于相当简单的结构来说是可以的,但是一旦您开始在更多数组的哈希中嵌套哈希,它很快就会变成一个混乱。因为我还没有找到一个好的print_r仿真,我自己写了一个。这对我的目的来说已经足够好了,不是太复杂了,我想我可以和别人分享一下,免得别人头疼。将输出与实际的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

Here's an example (made messy on purpose to show why the PHP print_r is so nice):

这里有一个示例(故意弄得很乱,以显示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)

Output of print_r (actually comprehensible by a human):

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
            )
    )

#6


2  

Check out the guide for debugging rails: http://guides.rubyonrails.com/debugging_rails_applications.html

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

hints: script/console is great to try stuff in the context of your app script/server --debugger to start the server with a debugger turned on, you can then use 'debug' in your code to break into an interactive shell

提示:脚本/控制台可以在应用程序脚本/服务器的上下文中尝试一些东西——调试器打开调试器启动服务器,然后可以在代码中使用“debug”来进入交互式shell

#7


1  

One approach I lean on a lot is this:

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

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

Easy to read, although it can get a little unwieldy for large objects.

很容易阅读,虽然对于大的对象它可能有点笨拙。

#8


0  

Guess I'm a little late to this, but what about logger.info [debug|warning]? Use this from Controllers and Models. It will show up in your log files (development.log when in dev mode); and the above mentioned <%= debug("str: " + str) %> for views.

我想我有点晚了,但是logger.info [debug|警告]呢?从控制器和模型中使用它。它将显示在您的日志文件(开发)中。在开发模式下登录);上面提到的<%= debug("str: " + str ") %>用于视图。

These aren't exact answers to your questions but you can also use script/console to load your rails app in to an interactive session.

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

Lastly, you can place debugger in a line of your rails application and the browser will "hang" when your app executes this line and you'll be able to be in a debug session from the exact line your placed your debugger in the source code.

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

#1


33  

In Rails templates you can do

在Rails模板中,您可以这样做。

<%= debug an_object %>

and it will do nice HTML PRE output.

它会做很好的HTML预输出。

#2


15  

Try using pp. You will need to require it in scripts (or in irb if your .irbc doesn't already do this):

尝试使用pp。您将需要在脚本中使用它(或者在irb中,如果您的。irbc还没有这样做的话):

require 'pp'

Then you can 'PrettyPrint' an object thus:

然后,你可以这样“美化”一个对象:

pp object

#3


10  

Instead of requiring 'pp' and using pp, you can simply do

不需要“pp”和使用pp,你可以做的很简单

p object

Tested example

测试的例子

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'

#4


6  

There's the method inspect which helps. Sometimes calling the to_s method on an object will help (to_s returns a string representation of the object). You can also query methods, local_variables, class_variables, instance_variables, constants and global_variables.

有一种方法可以帮上忙。有时调用对象上的to_s方法会有所帮助(to_s返回对象的字符串表示形式)。您还可以查询方法、local_variables、class_variables、instance_variables、constant和global_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"...]

#5


5  

I know this is an old post, but it is the first thing that Google pops up when searching for "Ruby equivalent of PHP print_r". I'm using Ruby in the command line mode, and there's really not a very good equivalent. "pp" is ok for fairly simple structures, but as soon as you start nesting hashes in arrays in hashes in more arrays, it turns into a jumble pretty fast. Since I haven't found a good emulation of print_r, I wrote one myself. It's good enough for my purposes, not overly complicated and I thought I'd share it to save other people some headache. Compare the output with the real PHP print_r

我知道这是一篇老文章,但这是谷歌在搜索“Ruby等价的PHP print_r”时首先出现的内容。我在命令行模式中使用Ruby,实际上并没有很好的对等。“pp”对于相当简单的结构来说是可以的,但是一旦您开始在更多数组的哈希中嵌套哈希,它很快就会变成一个混乱。因为我还没有找到一个好的print_r仿真,我自己写了一个。这对我的目的来说已经足够好了,不是太复杂了,我想我可以和别人分享一下,免得别人头疼。将输出与实际的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

Here's an example (made messy on purpose to show why the PHP print_r is so nice):

这里有一个示例(故意弄得很乱,以显示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)

Output of print_r (actually comprehensible by a human):

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
            )
    )

#6


2  

Check out the guide for debugging rails: http://guides.rubyonrails.com/debugging_rails_applications.html

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

hints: script/console is great to try stuff in the context of your app script/server --debugger to start the server with a debugger turned on, you can then use 'debug' in your code to break into an interactive shell

提示:脚本/控制台可以在应用程序脚本/服务器的上下文中尝试一些东西——调试器打开调试器启动服务器,然后可以在代码中使用“debug”来进入交互式shell

#7


1  

One approach I lean on a lot is this:

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

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

Easy to read, although it can get a little unwieldy for large objects.

很容易阅读,虽然对于大的对象它可能有点笨拙。

#8


0  

Guess I'm a little late to this, but what about logger.info [debug|warning]? Use this from Controllers and Models. It will show up in your log files (development.log when in dev mode); and the above mentioned <%= debug("str: " + str) %> for views.

我想我有点晚了,但是logger.info [debug|警告]呢?从控制器和模型中使用它。它将显示在您的日志文件(开发)中。在开发模式下登录);上面提到的<%= debug("str: " + str ") %>用于视图。

These aren't exact answers to your questions but you can also use script/console to load your rails app in to an interactive session.

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

Lastly, you can place debugger in a line of your rails application and the browser will "hang" when your app executes this line and you'll be able to be in a debug session from the exact line your placed your debugger in the source code.

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