Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use input name in return value variable name

Tags:

ruby

I'm trying to make this simple method return a value related to the name of its input. For instance if I give the method "people_array" it should return "people_array_of_arrays."

If I were using the method in IRB I would get something like:

people_array = ["George\tMichael", "Kim\tKardashian", "Kanyne\tWest"]
=> ["George\tMichael", "Kim\tKardashian", "Kanyne\tWest"]
make_array_of_arrays(people_array)
=> people_array_of_arrays
people_array
=> ["George\tMichael", "Kim\tKardashian", "Kanyne\tWest"]
people_array_of_arrays
=> [["George", "Micahel"], ["Kim", "Kardashian"], ["Kayne", "West"]]

I have written this so far, but have not been able to figure out how to return a nicely named array of arrays. All I could think of was string interpolation but that isn't exactly what I need.

def make_array_of_arrays(array)
    formatted_array = []
    array.each do |feed|
        mini_array = feed.split("\t")
        formatted_array.push(mini_array)
    end
    #{array}_of_arrays = formatted_array
end

I saw there was a method variablize, but that returns an instance variable which isn't exactly what I want. Any pointers?

like image 847
ovatsug25 Avatar asked Jul 24 '26 22:07

ovatsug25


1 Answers

I do not think that it can be easily done. Suppose you were able to define a local variable in some way within the method definition. But the scope of that local variable is limited to the method definition. So the moment you go outside of the method definition, the local variable name is gone. So in order to do it, you have to somehow get the binding information of the environment outside of the method definition, and define a local variable within that. I do not know if that is possible.

With instance variables, things get a little easier using instance_variable_set, but I am not sure how to implement it fully. First of all, getting the name of the original variable is tricky.

And what you are trying to do is not the right approach. You should think of different ways.


I think the best you can do is to use an instance variable instead of a local variable, and also give the name of the variable explicitly instead of the array itself:
def make_array_of_arrays(variable_name)
  array = instance_variable_get("@#{variable_name}")
  # Your code here
  instance_variable_set("@#{variable_name}_of_arrays", formatted_array)
end

@people_array = ["George\tMichael", "Kim\tKardashian", "Kanyne\tWest"]
make_array_of_arrays(:people_array)
@people_array_of_arrays
#=> [["George", "Micahel"], ["Kim", "Kardashian"], ["Kayne", "West"]]


This also might be useful.
like image 127
sawa Avatar answered Jul 28 '26 07:07

sawa