1

I am working on an rails app in which I need a comparison like:

url == "http://localhost:3000/admin/admin_login"

I am wondering that is there a way to compare like:

url == "*/admin/admin_login"
Ilya
  • 13,337
  • 5
  • 37
  • 53
Muhammad Faisal Iqbal
  • 1,796
  • 2
  • 20
  • 43

3 Answers3

5

You can use String#include?:

url = "http://localhost:3000/admin/admin_login"
url.include?("/admin/admin_login")
=> true

Other way is use String#end_with?:

url.end_with?("/admin/admin_login")
=> true

This works if you want to check if url ends with this argument.

Ilya
  • 13,337
  • 5
  • 37
  • 53
  • Note that this does not work as the wildcard `*/admin/admin_login` would: `"http://localhost:3000/admin/admin_login/foo".include?("/admin/admin_login")` gives you `true`. – nwk May 06 '16 at 16:11
5

You can use a regexp.

irb(main):001:0> url = "http://localhost:3000/admin/admin_login"
=> "http://localhost:3000/admin/admin_login"
irb(main):002:0> url =~ /admin\/admin_login\z/
=> 22
irb(main):003:0> url =~ /foo\/something_else\z/
=> nil
irb(main):004:0> "http://localhost:3000/admin/admin_login/bar" =~ /admin\/admin_login\z/
=> nil
nwk
  • 4,004
  • 1
  • 21
  • 22
  • 1
    I try and encourage people to use `x.match(y)` instead of `x =~ y` since the former is more clear. Also worth noting that `\z` is preferable to `$` for reasons [explained in this answer](http://stackoverflow.com/questions/577653/difference-between-a-z-and-in-ruby-regular-expressions). – tadman May 06 '16 at 17:48
  • Thanks for the suggestion to use `\z`! I've updated the answer accordingly. As for `x =~ y` vs. `x.match(y)`, I can't say I find one more clear than the other, so I'll just keep it as is. – nwk May 07 '16 at 09:32
0

You can use include? or []

value="http://localhost:3000/admin/admin_login"

value["/admin/admin_login"]
 => "/admin/admin_login" 
value["/admin/admin_login1"]
 => nil 
value[/\/admin\/admin_login/]
 => "/admin/admin_login" 
value.include?("/admin/admin_login")
 => true 
Horacio
  • 2,865
  • 1
  • 14
  • 24
  • when a value is nil then .include? will throw an error. How could i know value return strings and i can check with .include? method... – rohin-arka May 06 '16 at 17:04