`inject`不会在累加器中添加空格

时间:2015-12-19 17:14:17

标签: ruby string immutability

在此代码中:

"here are things"

返回值不应为str吗?我假设它将第一个值传递给累加器"here are things "。有没有办法返回using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using NetworksApi.TCP.CLIENT; namespace WindowsFormsApplication1 { public partial class Form1 : Form { Form1 client; public Form1() { InitializeComponent(); } private void textBox2_KeyDown(object sender, KeyEventArgs e) { } private void button2_Click(object sender, EventArgs e) { if (textBox3.Text!= "" &&textBox4.Text!="") { client = new Form1(); client.ClientName = textBox4.Text; client.ServerIp = textBox3.Text; client.Connect(); } else { MessageBox.Show("Fill it completely"); } } private void button3_Click(object sender, EventArgs e) { } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { System.Environment.Exit(System.Environment.ExitCode); } } }

2 个答案:

答案 0 :(得分:4)

  

我假设它将第一个值传递给累加器

正确,因为未定义初始值,集合的第一个元素将成为初始值。固定?提供初始值:

b = ['here', 'are', 'things']
b.inject('') { |memo, elem| memo + "#{elem} " } # => "here are things "

答案 1 :(得分:1)

在单词之前添加空格,就像这样。 结果中没有尾随空格。

["here", "are", "things"].inject { |str, v| str+=" #{v}" }
#=> "here are things"

你也可以做类似下面的事情但仍然没有尾随空格

['here', 'are', 'things'].inject { |m, e| "#{m} #{e}" }
#=> "here are things"