开发者

A ruby method to replace "="

I want to eliminate "=" sign for a particular reason. It might looks like this:

cat_that_has_name("Kelly").as(:kel开发者_StackOverflow社区ly)
kelly.do_something

The "as" method here is used to generate a method "kelly" that reference my cat. Could anyone help me with this?

Any suggestions will be appreciated.

Update:

Jorg was right, I've add a simple test to demonstrate my intention:

require "test/unit"

class AsTest < Test::Unit::TestCase
  def setup
    @cats = ["Kelly", "Tommy"]
  end

  def teardown
  end

  def test_as
    kelly1 =  get_cat("Kelly")
    get_cat("Kelly").as(:kelly2)
    assert_equal(kelly1.object_id, kelly2.object_id)
  end

  private
  def get_cat(name)
    @cats.each do |cat|
      if cat.to_s==name
        return cat
      end
    end
    return nil
  end
end


It's kind of hard to figure out what you actually want. If you want some sensible answers, you will have to provide a complete code example of what you want to achieve (for example, the code you posted is missing definitions for the cat_that_has_name and so_something methods). You will also need to post a complete specification of what exactly you expect the as method to do, with usage examples and ideally also with a testsuite. After all, how do we know if our answer is correct if you haven't defined what "correct" means?

The best I could decipher from your cryptic question is something like this:

class Object
  def as(name)
    s = self
    Object.send(:define_method, name) { s }
    Object.send(:private, name)
  end
end

But there is no way of knowing whether this works, because if I try to run your code example, I get a NoMethodError for cat_that_has_name and another NoMethodError for so_something.

Note also that your question is self-inconsistent: in your subject line you ask about a method to replace = (i.e. creating variables) but in your question you talk about creating methods, which would mean that you are looking for a replacement for def and not for =. Again, it would be much easier to answer correctly if there were a testsuite.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜