在Ruby / Rails中是否有类似于PHP的print_r函数的等效函数?

22

在PHP中可以使用以下方式:

print_r($var)vardump($var)

它们会打印有关变量的“易读”信息。

那么,在Ruby / Rails中是否有相应的函数/助手?

8个回答

35
在Rails模板中,可以这样做:
<%= debug an_object %>

它会生成漂亮的 HTML PRE 输出。


它在视图文件还是控制器中? - Harman

17

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

require 'pp'

你可以这样对一个对象进行“美化打印”:

pp object

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'

7

有一个方法叫做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"...]

6

我知道这是一篇旧文章,但当搜索“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

这是一个例子(特意弄乱以展示为什么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
            )
    )

2

1

我经常采用的一种方法是:

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

易于阅读,但对于大型对象可能有些笨重。


0

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

这些不是你问题的确切答案,但你也可以使用script/console将你的rails应用程序加载到交互式会话中。

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


我已经在控制器中编写了以下代码 ---- def index @users = User.all end--- 现在我想打印数组,我尝试使用 <%= debug (@users) %> 但是不起作用 :( - Harman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接