; nil
。
示例:users = User.all; nil
< p >irb
打印出最后一个执行语句的返回值;因此在这种情况下它只会打印出 nil
,因为 nil
是最后一个有效执行语句。
irb
打印最后一个执行语句的返回值;因此在此示例中,它将仅打印nil
,因为nil
是最后一个有效执行语句。
寻找如何消除irb/console输出的解决方案时,我在austinruby.com上也找到了一个答案:
消除irb输出:
conf.return_format = ""
默认输出:
conf.return_format = "=> %s\n"
限制为例如512个字符:
conf.return_format = "=> limited output\n %.512s\n"
irb --simple-prompt --noecho
--simple-prompt
- 使用简单提示符 - 只有>>
--noecho
- 阻止操作的结果输出在irb中执行以下命令可以正常运行:
irb_context.echo = false
在这里,将以下内容添加到你的~/.irbrc文件中:
require 'ctx'
require 'awesome_print'
module IRB
class Irb
ctx :ap do
def output_value()
ap(@context.last_value)
end
end
ctx :puts do
def output_value()
puts(@context.last_value)
end
end
ctx :p do
def output_value()
p(@context.last_value)
end
end
ctx :quiet do
def output_value()
end
end
end
end
def irb_mode(mode)
ctx(mode) { irb }
end
irb(main):001:0> { this:'is a complex object', that:[ { will:'probably'}, { be:'good to read' } ], in:{ some:{ formatted:'way'} } }
=> {:this=>"is a complex object", :that=>[{:will=>"probably"}, {:be=>"good to read"}], :in=>{:some=>{:formatted=>"way"}}}
...yep, just what you expect.
awesome_print
mode:
irb(main):002:0> irb_mode(:ap)
irb#1(main):001:0> { this:'is a complex object', that:[ { will:'probably'}, { be:'good to read' } ], in:{ some:{ formatted:'way'} } }
=> {
:this => "is a complex object",
:that => [
[0] {
:will => "probably"
},
[1] {
:be => "good to read"
}
],
:in => {
:some => {
:formatted => "way"
}
}
}
现在一切都打印得非常棒!:)
静默模式:
irb#1(main):002:0> irb_mode(:quiet)
irb#1(main):001:0> { this:'is a complex object', that:[ { will:'probably'}, { be:'good to read' } ], in:{ some:{ formatted:'way'} } }
irb#1(main):002:0>
...哇,完全没有输出?太好了。
无论如何,您可以添加任何您喜欢的模式,并且当您完成该模式时,只需退出即可返回上一个模式。
希望这有所帮助!:)
此外,根据您的需求,可以考虑使用 quietly
或 silence_stream
来抑制总体输出,而不仅仅是在 irb/console 中抑制输出:
silence_stream(STDOUT) do
users = User.all
end
注意: Rails 5+已删除silence_stream
注意: quietly
在Ruby 2.2.0版本中将被弃用,最终将被删除 (感谢BenMorganIO!)
更多信息可以在这里找到。
如上所述,silence_stream
不再可用,因为它不是线程安全的。没有一个线程安全的替代方案。但是,如果您仍然想使用silence_stream
并且知道它不是线程安全的,并且没有以多线程方式使用它,您可以手动将其添加回初始化程序。
config/initializer/silence_stream.rb
# Re-implementation of `silence_stream` that was removed in Rails 5 due to it not being threadsafe.
# This is not threadsafe either so only use it in single threaded operations.
# See https://api.rubyonrails.org/v4.2.5/classes/Kernel.html#method-i-silence_stream.
#
def silence_stream( stream )
old_stream = stream.dup
stream.reopen( File::NULL )
stream.sync = true
yield
ensure
stream.reopen( old_stream )
old_stream.close
end
quietly
已被弃用并将被移除。 - BenMorganIO将nil
作为虚假返回值添加以消除输出是可行的,但我更喜欢有一些指示发生了什么。一个简单的计数通常就足够了。很多时候,这很容易通过添加count
函数来完成。因此,当我对一堆Discourse主题进行操作时,我不想要每个主题对象的打印输出。所以我在循环末尾添加.count
:
Topic.where(...).each do |topic|
...
end.count
如果我只是分配某些东西,那么就是同样的事情:
(users = User.all).count
完全静音输出(或使其成为静态的,如nil
),会使我失去有用的反馈。
users = User.all; 0
。 - BobUsers.all.count
一样,只有一行输出,如果你想将输出存储在变量中,可以这样做:users = User.all; Users.all.count
。 - Tasawar Hussain