Skip to content

Instantly share code, notes, and snippets.

@timuruski
Last active December 21, 2022 17:20
Show Gist options
  • Save timuruski/c14f4565ae833c00a66a to your computer and use it in GitHub Desktop.
Save timuruski/c14f4565ae833c00a66a to your computer and use it in GitHub Desktop.

Revisions

  1. Tim Uruski revised this gist May 9, 2014. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions string_validation.rb
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,6 @@
    # If you want to check whether a string matches a regular expression,
    # but not return the match data, you can just use === the case equality operator.

    # Bad
    !! ('foobar' =~ /bar/) #=> true
    !! ('foo' =~ /bar/) #=> false
  2. Tim Uruski revised this gist May 9, 2014. 1 changed file with 4 additions and 3 deletions.
    7 changes: 4 additions & 3 deletions string_validation.rb
    Original file line number Diff line number Diff line change
    @@ -6,13 +6,14 @@
    /bar/ === 'foobar' #=> true
    /bar/ === 'foo' #=> false

    # This makes sense if you think about it in a case statement.
    # This makes sense if you think about it in a case statement and === for RegExp.
    case 'foobar'
    when /foo/
    'makes sense'
    "makes sense"
    end

    # Implementing === on String to match RegExp is less sensical.
    case /foo/
    when 'foobar'
    'doesn't make sense'
    "doesn't make sense"
    end
  3. Tim Uruski revised this gist May 9, 2014. 1 changed file with 15 additions and 8 deletions.
    23 changes: 15 additions & 8 deletions string_validation.rb
    Original file line number Diff line number Diff line change
    @@ -1,11 +1,18 @@
    pattern = /bar/

    # Bad
    !! ('foobar' =~ /bar/)
    #=> true
    !! ('foo' =~ /bar/)
    #=> false
    !! ('foobar' =~ /bar/) #=> true
    !! ('foo' =~ /bar/) #=> false

    # Good
    pattern === string
    #=> true
    /bar/ === 'foobar' #=> true
    /bar/ === 'foo' #=> false

    # This makes sense if you think about it in a case statement.
    case 'foobar'
    when /foo/
    'makes sense'
    end

    case /foo/
    when 'foobar'
    'doesn't make sense'
    end
  4. Tim Uruski revised this gist May 9, 2014. 1 changed file with 8 additions and 2 deletions.
    10 changes: 8 additions & 2 deletions string_validation.rb
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,11 @@
    pattern = /bar/

    # Bad
    !! (string =~ pattern)
    !! ('foobar' =~ /bar/)
    #=> true
    !! ('foo' =~ /bar/)
    #=> false

    # Good
    pattern
    pattern === string
    #=> true
  5. Tim Uruski created this gist May 9, 2014.
    5 changes: 5 additions & 0 deletions string_validation.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    # Bad
    !! (string =~ pattern)

    # Good
    pattern