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

java - How to pass parameters between Request-Scoped Controllers? -

actionscript 3 - Flex: moving a point with rotation doesnt change the point XY? -

string - what is the difference between "some" == "some\0" and strcmp("some","some\0") in c++? -