隣の要素同士を引き算したい - by shigemk2
で
val is = List(1, 2, 3, 4)
is.sliding(2).toList.map { case List(a, b) => b - a }
というのを見かけ、Ruby でもできたよな。と思ったもののメソッドどれだっけ?w
という状態に
irb(main):002:0> [1,2,3,4].methods.sort
=> [:!, :!=, :!~, :&, :*, :+, :-, :<<, :<=>, :==, :===, :=~, :[], :[]=, :__id__,
:__send__, :all?, :any?, :assoc, :at, :bsearch, :chunk, :class, :clear, :clone, :collect,
:collect!, :collect_concat, :combination, :compact, :compact!, :concat, :count, :cycle,
:define_singleton_method, :delete, :delete_at, :delete_if, :detect, :display, :drop,
:drop_while, :dup, :each, :each_cons, :each_entry, :each_index, :each_slice, :each_with_index,
:each_with_object, :empty?, :entries, :enum_for, :eql?, :equal?, :extend, :fetch, :fill,
:find, :find_all, :find_index, :first, :flat_map, :flatten, :flatten!, :freeze, :frozen?,
:grep, :group_by, :hash, :include?, :index, :inject, :insert, :inspect, :instance_eval,
:instance_exec, :instance_of?, :instance_variable_defined?, :instance_variable_get,
:instance_variable_set, :instance_variables, :is_a?, :itself, :join, :keep_if, :kind_of?,
:last, :lazy, :length, :map, :map!, :max, :max_by, :member?, :method, :methods, :min, :min_by,
:minmax, :minmax_by, :nil?, :none?, :object_id, :one?, :pack, :partition, :permutation, :pop,
:private_methods, :product, :protected_methods, :public_method, :public_methods, :public_send,
:push, :rassoc, :reduce, :reject, :reject!, :remove_instance_variable, :repeated_combination,
:repeated_permutation, :replace, :respond_to?, :reverse, :reverse!, :reverse_each, :rindex,
:rotate, :rotate!, :sample, :select, :select!, :send, :shift, :shuffle, :shuffle!, :single
ton_class, :singleton_method, :singleton_methods, :size, :slice, :slice!, :slice_after,
:slice_before, :slice_when, :sort, :sort!, :sort_by, :sort_by!, :taint, :tainted?, :take,
:take_while, :tap, :to_a, :to_ary, :to_enum, :to_h, :to_s, :transpose, :trust, :uniq, :uniq!,
:unshift, :untaint, :untrust, :untrusted?, :values_at, :zip, :|]
で、これだった。
each_cons (Enumerable) - Rubyリファレンス
irb(main):009:0> [1,2,3,4].each_cons(2){|a,b| puts b-a}
1
1
1
=> nil
こうしたほうがわかりやすいか?
irb(main):010:0> [1,2,3,4].each_cons(2){|a,b| puts "#{b}-#{a} #{b-a}"}
2-1 1
3-2 1
4-3 1
=> nil
探しているときに気がついたのだけど
こういうメソッドもあったのか。
instance method Enumerable#slice_before (Ruby 2.1.0)