开发者

Finding the whether the element of the Array is last or not in ruby

开发者 https://www.devze.com 2023-03-21 20:02 出处:网络
Lets suppose we have an array p = String.new a = [\'d\',\'e\',\'f\',\'g\',\'h\'] a.each do |val开发者_运维知识库ue|

Lets suppose we have an array

p = String.new
a = ['d','e','f','g','h']
a.each do |val开发者_运维知识库ue|
 p << value
 p << "%" if value is not last
end

I need to determine whether the a['h'] is the last index value or not?

Is there a shortcut way to find it like a.is_last?()


Using your specific example, you can just use Array.join. You can then replace your example with:

a = ["d", "e", "f", "g", "h"]
p = a.join("%") # d%e%f%g%h


I have done this in the way

p = String.new
a = ['d','e','f','g','h']
a.each do |value|
 p << value
 p << "%" if a.last != value
end

I need other then this?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号