1

I am writing a class which involves multiple methods for certain purpose. But however the final result of each method is saved in an instance variable so that the other methods can access them. In ruby however method call however returns the last value and this approach can also adopted. But I am confused as which approach is programmatically right and more ruby like.

An example for my code would be like this

Approach1:- Method call

class Foo
  def cat
    "This is a cat"
  end
  def bigcat
     cat
  end
end
mycat = Foo.new
mycat.cat
mycat.bigcat
Output:- This is a cat
         This is a cat

Approach2:- Instance variable

class Foo
  def cat
    @cat_talk = "This is a cat"
  end
  def bigcat
     @cat_talk
  end
end
mycat = Foo.new
mycat.cat
mycat.bigcat



Output:- This is a cat
         This is a cat

The above example may seem simple but in my ruby class the implementation is much more complex and larger.

2 Answers 2

1

Instead of defining the method bigcat you may rename your instance variable and use a accessor method.

Example based on dimitris answer:

class Foo
  def cat
    @bigcat ||= "This is a cat"
  end
  attr_reader :bigcat
end

mycat = Foo.new
mycat.cat
mycat.bigcat

If you want to keep your variable name, you could combine it with an alias:

class Foo
  def cat
    @cat_talk ||= "This is a cat"
  end
  attr_reader :cat_talk
  alias :bigcat :cat_talk
end

mycat = Foo.new
mycat.cat
mycat.cat_talk
mycat.bigcat

Beyond your question, just for information: You could also define a writter method with attr_writer.

Sign up to request clarification or add additional context in comments.

1 Comment

I thought of tat to be honest, but I think that the intention is not to "wrap" bigcat, but to do other things as well. the attr reader is a nice addition in either case
1

I'd suggest something like this (memoising):

class Foo
  def cat
    @cat_talk ||= "This is a cat"
  end
  def bigcat
     cat
  end
end

mycat = Foo.new
mycat.cat
mycat.bigcat

Output:- This is a cat
         This is a cat

Generally IMHO it's better to call methods when they wrap a variable instead of accessing them directly. If you want for example to capitalize it, you can just wrap cat and leave the actual data intact.

2 Comments

Thanks for the tip sir.. Is memoising == caching ?
For the purpose of the discussion yes, en.wikipedia.org/wiki/Memoization. Essentially you do not want to assign every time it's called.

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.