I have a method I wish to use, to be make my code a little more legible (in my opinion)
My code:
def format_chosen_address(address)
# Add country before the postcode
postcode = address.split("\n").last
country = postcode.is_welsh? ? 'WALES' : 'ENGLAND'
address.split("\n").insert(-2, country).join(' ')
end
def is_welsh?
welsh_postcodes = ['SA1 6AZ', 'SA7 9BR', 'CF10 1AX']
welsh_postcodes.include? self
end
I get the following exception:
NoMethodError: undefined method `is_welsh?' for "SA1 6AZ":String
Where have I gone wrong because thought self and boolean methods could be used this way?
I can get it to work if I do the following, but it doesn't read as nice to me.
def format_chosen_address(address)
# Add country before the postcode
postcode = address.split("\n").last
country = is_welsh?(postcode) ? 'WALES' : 'ENGLAND'
address.split("\n").insert(-2, country).join(' ')
end
def is_welsh?(postcode
welsh_postcodes = ['SA1 6AZ', 'SA7 9BR', 'CF10 1AX']
welsh_postcodes.include? postcode
end
is_welsh?method will only work like that if you define it inside theStringclassis_orhas_prefixes for predicate methods.postal_code.welsh?postal code starts looking less and less like a primitive string and more like it's own class of thing, so even if consideration determines "not worth it's own class" it's at least worth that consideration; a postal code class may be too specific but you might see other classes that make sense and, say, promote address (there's a lot of functionality for address in here, as well) instead of the specific postal code.