ruby - How to call different methods as given in an array -
especially when working structs, nice able phone call different method per each element in array, this:
array = %w{name 4 tag 0.343} array.convert(:to_s, :to_i, :to_sym, :to_f) # => ["name", 4, :tag, 0.343]
are there simple one-liners, activesupport methods, etc. easily?
i this:
class array def convert(*args) map { |s| s.public_send args.shift } end end array = %w{name 4 tag 0.343} args = [:to_s, :to_i, :to_sym, :to_f] array.convert(*args) #=> ["name", 4, :tag, 0.343] args #=> [:to_s, :to_i, :to_sym, :to_f]
i included lastly line show convert
leaves args
unchanged, though args
emptied within convert
. that's because args
splatted before beingness passed convert
.
as per @arup's request, i've benchmarked , solutions:
class array def sq_convert(*args) zip(args).map { |string, meth| string.public_send(meth) } end def lf_convert(*args) map { |s| s.public_send args.shift } end end require 'benchmark' n = 1_000_000 array = %w{name 4 tag 0.343} args = [:to_s, :to_i, :to_sym, :to_f] benchmark.bmbm(15) |x| x.report("arup's super-quick :") { n.times { array.sq_convert(*args) } } x.report("cary's lightning-fast:") { n.times { array.lf_convert(*args) } } end # rehearsal ---------------------------------------------------------- # arup's super-quick : 2.910000 0.000000 2.910000 ( 2.922525) # cary's lightning-fast: 2.150000 0.010000 2.160000 ( 2.155886) # ------------------------------------------------- total: 5.070000sec # user scheme total real # arup's super-quick : 2.780000 0.000000 2.780000 ( 2.784528) # cary's lightning-fast: 2.090000 0.010000 2.100000 ( 2.099337)
ruby arrays map
No comments:
Post a Comment