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