I have this code
if self.name.starts_with?('Bronze') || self.name.starts_with?('Silver') ||self.name.starts_with?('Gold')
Is there a way to pass all of these strings in one go rather than lots of OR as I may have to expand on this?
String#start_with?
accepts arbitrary number of arguments. You don't need to use ||
.
'Silver medal'.start_with?('Bronze', 'Silver', 'Gold')
# => true
'Hello medal'.start_with?('Bronze', 'Silver', 'Gold')
# => false
No, start_with
takes a string or regex.
I'd find the continuously-expanding regex annoying.
Until I discovered I was totally wrong as per @falsetru, I'd have done it like this:
%w[Bronze Silver Gold].any? { |s| name.start_with? s }
I'd put the array of words into a variable or constant (or method, I suppose), though.
Then I'd put the logic into a method on whatever it is with the name
property, the name of which depends on context. This makes this trivially testable, extensible, and encapsulated.
def precious_metal?
self.name.starts_with? precious_metals
end
...
if precious_metal?
# Some logic
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With