Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 索引定位方法_Ruby On Rails_Ruby - Fatal编程技术网

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我的答案有帮助吗?我稍微整理了一下你的问题,但第二个示例中的代码格式保持不变,以强调一点:保持代码正确缩进,你会发现它有助于识别丢失的终止符。任何像样的源代码编辑器都会帮助您保持缩进,所以如果您不使用缩进编辑器,那么就开始吧。这会让你的生活轻松很多。