ruby - Generic method to get id's from either a single object or collection -



ruby - Generic method to get id's from either a single object or collection -

i want create generic method take either single object or collection, , homecoming array of id's, , actual id take object/collection passed in parameter.

example:

a = [] << get_ids("car_id", some_object) << get_ids("user_id", some_collection) def self.get_ids(id_name, obj) # ?? end

this needs metaprogramming know, how figure out if collection or not? send message check if "id_name" property?

also, need type of functionality, thought of making generic can re-use it. have major performance implications?

def self.get_ids(id_name, obj) if obj.is_a? enumerable obj.collect {|e| e.send(id_name) } else obj.send(id_name) end end

alternatively,

def self.get_ids(id_name, *objs) objs.collect {|e| e.send(id_name) } end ... << get_ids("car_id", some_object) << get_ids("user_id", *some_collection)

ruby

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

c# - Can ProtoBuf-Net deserialize to a flat class? -

javascript - Change element in each JQuery tab to dynamically generated colors -