0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

配列の繰り返し処理でのエラー

Posted at
lines=[r1,r2,r3,r4,r5]
g1=r2-r1  #lines[1]-lines[0]
g2=r3-r2  #lines[2]-lines[1]
g3=r4-r3  #lines[3]-lines[2]
g4=r5-r4  #lines[4]-lines[3]

puts g1
puts g2
puts g3
puts g4

という処理があり

なんとか簡略化出来ないか試行錯誤し

days = [] #空の配列
  n=0  
  while n<lines.length               #配列の要素の数だけ繰り返し
  days << lines[n+1]-lines[n]        #新しく作りたい配列の要素
  n+=1
  end

  days.each do|n|
  puts n
  end

としたがエラーが出てしまった。

undefined method `-' for nil:NilClass (NoMethodError)

teratailで質問をしたところ
配列の要素n<lines.lengthが最大値4であり
最大値4の時days << lines[n+1]-lines[n]lines[5]という存在しない
nilになっておりnilには演算子が使えないのでエラーが出るということでした。。。

なので条件をn<lines.length-1とすればエラーなく実行できます。

合わせて他の方からeach_consというメソッドを教えていただいてこれを使うと

days = lines.each_cons(2).map{ |a, b| b - a }
days.each do |n|
puts n
end

と短く実装できます。
とても便利なものを教えていただいて感謝です。

each_consの使い方

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?