0

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.

7
  • What do you mean by object_name? In your example would they be Big, Medium and Small? Commented Jan 14, 2014 at 9:49
  • Yes, yes, they would be Big, Medium, and Small. Commented Jan 14, 2014 at 9:53
  • I don't think it is possible what you want to achieve since those are the names of the variables which have been assigned to the Picture objects: it is impossible for the Picture know which variable you are using. Commented Jan 14, 2014 at 9:56
  • Well, any way to identify which object (not class) is calling this method would be very helpful. I just need the case operator to work. Commented Jan 14, 2014 at 9:57
  • Then you will have to change the class to add a setter for the name attribute, as you did for size. Commented Jan 14, 2014 at 10:00

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.