0

I have some methods that contain lots of different combinations of the same logic. To clean it up, I would like to define each test just once.

class Sentence < ApplicationRecord

#Gathers options hash for sentence
def options
    { 
        pronoun: subject.pronoun,
        ...
        }
end

#gives auxiliary verb based on sentence options 
def aux
    third_person = ["he", "she", "it"].include?(options[:pronoun])

    aux = "does" if third_person #just an example 
    ...
end
...

This works fine, but I am trying to pull this out of the aux method to use in other methods.

#this works
@@third_person = ["he", "she", "it"].include?("he")
#this says that there is no options method
@@third_person = ["he", "she", "it"].include?(options[:pronoun])

Does anyone know, what I'm missing?

4
  • 1
    When we're talking about "cleaning things up", one thing you want to pay careful attention to is declaring unchanging, but throw-away arrays inside methods like this. Use a constant like PREFIXES = %w[ he she it ] and then use that array over and over. You could also use a regular expression if there's some ambiguity or performance concerns. Likewise, returning a temporary hash that's used once is very inefficient, especially if the hash never changes. Commented Sep 29, 2016 at 15:27
  • 2
    The context of the test code isn't clear. Where are you running that? Also why are you declaring class-style @@ variables? Commented Sep 29, 2016 at 15:30
  • I agree with @tadman that you should separate the pronouns to constant variable. Also use freeze method so it cannot be modified. PREFIXES = %w(he she it).freeze Commented Sep 29, 2016 at 15:33
  • Ok, cool no problem with the constant because it won't be changing. I think I'm a bit confused with the class variable though. It doesn't seem like its capable of doin what I want. I have an instance of sentence. The options method gets the options for that instance. I want to define a test that uses an instance option once and have access to it from the other instance methods. I guess another instance method would be the way to go? Commented Sep 29, 2016 at 15:44

1 Answer 1

1

You are not calling the instance method options on instance of class Sentence.

You have to call it this way:

sentence = Sentence.new
['he', 'she', 'it'].include?(sentence.options[:pronoun])
Sign up to request clarification or add additional context in comments.

1 Comment

That's the right answer to my question, but now I realise that I was going about everything the wrong way. Thanks for the quick answers, it helped me rethink my code.

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.