简体   繁体   English

如何在ruby中将条件循环连接字符串

[英]How to concatenate strings with condition each loop in ruby

I'm trying to concatenate 2 consecutive strings if any string length is less than 4 characters, but I'm not successful. 如果任何字符串长度小于4个字符,我正在尝试连接2个连续的字符串,但是我不成功。

The code I have so far is: 到目前为止,我的代码是:

strings = ['abnhs', 'iuu', 'poioyw', 'tyr', 'mmkaud']
strings.each do |w|
  if w.length < 4
    temp = w
    next
  end    
  w = temp + w 
  puts w
end

Expected output is: 预期输出为:

abnhs
iuupoioyw
tyrmmkaud

Thanks in advance for any help 预先感谢您的任何帮助

You need to declare the temp variable outside of your each block. 您需要在每个块之外声明temp变量。 Try this: 尝试这个:

strings = ['abnhs', 'iuu', 'poioyw', 'tyr', 'mmkaud']
temp = ''
strings.each do |w|
  if w.length < 4
    temp = w
    next
  end    
  w = temp + w 
  puts w
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM