سؤال

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