문제

Can anyone tell me a more efficient way of doing url.downcase.include? "some string" in the following context?

def source
  return if url.nil?

  source = nil

  if url.downcase.include? 'techcrunch.com' or url.downcase.include? 'tcrn.ch'
    source = 'techcrunch'
  end

  source
end

I'm just starting out with Ruby, so if you have any other tips I'd appreciate them.

Thank you so much, Pamela

도움이 되었습니까?

해결책

If you meant computational efficiency yours is about as good as it gets except perhaps calling .downcase twice. But really performance wise you will not get much improvement from anything in such a simple case.

If you are looking for a shorter way to write your implementation, this is probably about as short as possible:

def source(url)
  url =~ /techcrunch\.com|tcrn\.ch/i && 'vimeo'
end

source('www.stackoverflow.com') # => nil
source('www.techcrunch.com') # => "vimeo"

다른 팁

def source
  return unless url
  downcased_url = url.downcase
  'vimeo' if %w[techcrunch.com tcrn.ch].any? { |u| downcased_url.include? u }
end
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top