ruby - 用 ruby 阻止内部插值

标签 ruby arrays codeblocks string-interpolation

我正在编写一个简单的程序,它要求用户输入一个数组并吐出该数组及其平均值。真的很简单,我没有遇到任何问题。

最后我想出了:(在这个例子中我将只使用一个随机数组而不是用户输入的代码)

array = [1,2,3]
sum = array.inject(:+)
average = sum.to_f/array.length
puts "The numbers you entered in the array were: #{array.join(" ")}"
puts "The average of those numbers are: #{average}"

输出是预期的并给我:

The numbers you entered in the array were: 1 2 3
The averages of those numbers are: 2.0

但是,当我第一次尝试对此进行编码时,我试图真正巧妙地进行简单的分配,并且我尝试在插值内部进行插值。我使用了这段代码:

对于上面代码中的第四行,我使用了:

puts "The numbers you entered in the array were: #{array.each{|num| print "#{num} "}}" 

输出:

1 2 3 The numbers you entered in the array were: [1, 2, 3]

所以我认为在插值内部的 block 内进行插值可能存在问题。 所以我然后运行以下代码来测试插值内的 block 。

puts "The numbers you entered in the array were: #{array.each{|num| print num}}"

输出:

123The numbers you entered in the array were: [1, 2, 3]

任何人都可以解释为什么 proc 首先在插值内部执行,打印然后 puts 发生。此外,当我从未对数组调用 .inspect 时,为什么它会将数组置于 array.inspect 形式。

最佳答案

您想回答的问题

当您使用变量插值时,要插值的值将在原始字符串之前解析。

在这种情况下,您的 Array.each 正在做它的事情并打印出“1”,然后是“2”,最后是“3”。它返回 [1, 2, 3] 的原始数组

output> 123 # note new line because we used print

现在您的插值已解决,其余的 puts 完成并使用 [1, 2, 3] 的返回值并打印:

output> The numbers you entered in the array were: [1, 2, 3]\n

获取最终输出:

output> 123The numbers you entered in the array were: [1, 2, 3]\n

每个人都想回答的问题:)

http://www.ruby-doc.org/core-2.1.4/Array.html#method-i-each

当用一个 block 调用 Array.each 时,返回的是 self。

这对你来说是“坏”的,因为你不希望 self 返回。它总是会返回相同的东西,即您的原始数组。

puts "The numbers you entered in the array were: #{array.each{|num| num*2}}"
The numbers you entered in the array were: [1, 2, 3] # WAT?

正如 Sergio Tulentsev 所说,使用 .map 和 .join

puts "The numbers you entered in the array were: #{array.map{|num| num*2}.join(' ')}"
The numbers you entered in the array were: 2 4 6

关于ruby - 用 ruby 阻止内部插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26932766/

相关文章:

java - 在一个数组中,是否至少有一个数字比另一个数组中的所有其他数字大?

c++ - <<method name>> 未在此范围内为私有(private)静态方法声明

ruby - rbenv:未安装版本 `2.2.3'(由 RBENV_VERSION 环境变量设置)

ruby - ruby 和 activerecord 中的 AES 解密

java - 替换数组中的值

c - 将原始索引存储在数组中

c++ - CodeBlocks c++ - 不能使用线程,因为编译器不支持它

c 代码不适用于带有 float 的 Turbo C++

ruby-on-rails - 在 webrick 服务器的生产模式下运行 rails

ruby-on-rails - before_filter 运行多个方法