Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass multiple strings to ruby starts_with?

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?

like image 781
Gareth Burrows Avatar asked Jan 22 '15 14:01

Gareth Burrows


2 Answers

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
like image 165
falsetru Avatar answered Nov 20 '22 23:11

falsetru


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
like image 20
Dave Newton Avatar answered Nov 21 '22 00:11

Dave Newton