Reputation: 328
I have the following problem. I would like to have a method, let's call it method_A that check the object name that call method_A.
This is a simple reference, but what I'd be doing would be much more complicated than this, I understand that there's an alternative that can solve what I need in a much better way, but alas the code almost done, and I don't have enough time to tweak around much. Anyway, here it goes:
class Picture
attr_accessor :size
def resize
name = self.get_object_name_here
case name
when Big #Can be string or variable, I don't mind
self.size *= .5
when Medium
when Small
self.size *= 2
else
end
def get_object_name_here
object_name
end
end
Big = Picture.new
Medium = Picture.new
Small = Picture.new
Big.size = 10
Medium.size = 10
Small.size = 10
Big.resize => 5
Medium.resize => 10
Small.resize => 20
If there's a way to just do
name = object_name
That would be very HELPFUL
Greatly Appreciated!
Edit: Sorry for the capitalized Big, Medium, Small. They are typos.
Upvotes: 0
Views: 132
Reputation: 3999
You'll have to change the definition of your class
class Picture
attr_accessor :size, :name
def initialize(name)
@name = name
@size = 10
end
def resize
case name
when "Big"
self.size *= 0.5
when "Medium"
when "Small"
self.size *= 2
else
end
end
end
The initialize
method will be called by Ruby when you use new
passing along all the arguments. You can use this class like this:
big = Picture.new("Big")
medium = Picture.new("Medium")
small = Picture.new("Small")
puts "before resize"
puts big.size
puts medium.size
puts small.size
big.resize
medium.resize
small.resize
puts "after resize"
puts big.size
puts medium.size
puts small.size
results in
before resize
10
10
10
after resize
5.0
10
20
Upvotes: 1