0

I'm trying to format hex strings using an inherited format method. I'm a bit of a Ruby-noob, any help is appreciated.

class Bar
  def alter_the_variable attribute_name
    attribute = method(attribute_name)
    formatted = "%.4x" % attribute.call.hex
    puts formatted    # => 00f3
    attribute = formatted   # What I "want" to be able to do, but
                            # doesn't work because attribute is a local variable

    #attribute.owner.send(:h=, formatted)   # Doesn't work either, gives:
                                            # in `send': undefined method `h=' for Foo:Class (NoMethodError)
  end
end

class Foo < Bar
  def initialize
    @h = "f3"
  end

  def h
    @h
  end

  def h= val
    @h = val
  end
end

f = Foo.new
puts f.h    # => f3
f.alter_the_variable :h
puts f.h    # => f3

1 Answer 1

1

Here's one way to do what you wanted to do:

def alter_the_variable attribute_name
  current_value = send(attribute_name)
  formatted_value = "%.4x" % current_value.hex
  send (attribute_name.to_s+'=').to_sym, formatted_value
end
Sign up to request clarification or add additional context in comments.

1 Comment

I guess that my attribute.owner in front of send was referring to the Foo class, not the Foo instance. Thank you, sir. You are a scholar and a gentleman.

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.