Ruby:如何为数组和哈希制作 IRB 打印结构 [英] Ruby: How to make IRB print structure for Arrays and Hashes

查看:40
本文介绍了Ruby:如何为数组和哈希制作 IRB 打印结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 irb 中创建一个新的数组/散列时,它会打印出一个很好的格式来显示结构,例如.

When I make a new array/hash in irb, it prints out a nice format to show the structure, ex.

["value1", "value2", "value3"]
{"key1" => "value1"}

...但是当我尝试使用 puts 打印出我的变量时,我让它们折叠起来:

... but when I try to print out my variables using puts, I get them collapsed:

value1
value2
value3
key1
value1

我认为 puts 不是我想要的正确命令,但什么是?我希望能够以第一种格式而不是第二种格式在 irb 中查看我的变量.

I gather that puts is not the right command for what I want, but what is? I want to be able to view my variables in irb in the first format, not the second.

推荐答案

您可以使用 inspect 方法:

a=["value1", "value2", "value3"]
puts a.inspect

或者,更好的是,使用 pp(漂亮的打印)库:

Or, even better, use the pp (pretty print) lib:

require 'pp'
a=["value1", "value2", "value3"]
pp a

这篇关于Ruby:如何为数组和哈希制作 IRB 打印结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆