Skip to content

Instantly share code, notes, and snippets.

@kachick
Created September 25, 2012 14:55
Show Gist options
  • Save kachick/3782432 to your computer and use it in GitHub Desktop.
Save kachick/3782432 to your computer and use it in GitHub Desktop.
Array 要素すべてが#==で一致するか調べる
values = [1, 2, 3]
others = [1.0, 2.0, 3.0]
(values.length == others.length) && values.each_with_index.all?{|v, idx|v == others.fetch(idx)}
@KitaitiMakoto
Copy link

ありがとうございます!
Array#zipがあるのだから、そんな感じでこれもすっきり書けてほしいですねえ。

実は最初言っていたのはこんなののつもりでした。

values = 3.times.map {rand(3) + 1}
p values
puts values.all? {|value| value == values.first}

values.firstがなんかかっこわるいなあと感じています。

@kachick
Copy link
Author

kachick commented Sep 25, 2012

なるほど、同じArrayの中で、ですか
==による比較では無いのですが、例のようなFixnum等だけが対象だったらuniq活用するのもありかもしれません。

values = 3.times.map {rand(3) + 1}
p values
puts values.uniq.length == 1

@KitaitiMakoto
Copy link

こちらの方がすっきりした感じですね!
👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment