Ruby on rails 索引定位方法
为了学习,我想打印出数组所在的元素:Ruby on rails 索引定位方法,ruby-on-rails,ruby,Ruby On Rails,Ruby,为了学习,我想打印出数组所在的元素: a = [1,2,3] a.each_with_index do |element, index| print "#{element} is at position #{index}" end 这是可行的,但我的目标是用一种方法来包装它。我试着这样做: def addValue(a) a.each_with_index do |element, index| print "#{element} is at position #{index}" e
a = [1,2,3]
a.each_with_index do |element, index|
print "#{element} is at position #{index}"
end
这是可行的,但我的目标是用一种方法来包装它。我试着这样做:
def addValue(a)
a.each_with_index do |element, index|
print "#{element} is at position #{index}"
end
但这给了我一个语法错误
我该怎么做?你没有关闭你的方法。应该是:
def addValue(a)
a.each_with_index do |element, index|
print "#{element} is at position #{index}"
end
end
确保始终正确缩进代码以防止此类错误 @user3706202我的答案有帮助吗?我稍微整理了一下你的问题,但第二个示例中的代码格式保持不变,以强调一点:保持代码正确缩进,你会发现它有助于识别丢失的终止符。任何像样的源代码编辑器都会帮助您保持缩进,所以如果您不使用缩进编辑器,那么就开始吧。这会让你的生活轻松很多。