Skip to content

Instantly share code, notes, and snippets.

@daniellockard
Created February 6, 2011 21:57
Show Gist options
  • Save daniellockard/813758 to your computer and use it in GitHub Desktop.
Save daniellockard/813758 to your computer and use it in GitHub Desktop.
adds an each_word function to ruby
class String
def each_word
self.split.each { |value|
return value if yield(value)
}
end
end
@MarviCode
Copy link

So if no code block is passed to the method, an Enumerator object will be instantiated, instead of raising a "no block given" exception such as LocalJumpError.

class String 
  def each_word
    if block_given?
      self.split.each {|value| return value if yield(value) }
    else
      self.split.each
    end
  end
end

@daniellockard
Copy link
Author

This gist is 12 years old.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment