开发者

Checking if string is like another in Rails

In rails is there a way of doing something like the following...

if @var == "string%"

The % meaning that there can be anything at the end o开发者_如何转开发f the string but as long as it starts with "string" it will return true.

Any help is much appreciated.


There is String#start_with?

http://rubydoc.info/docs/ruby-core/1.9.2/String#start_with%3F-instance_method


You could use a regexp match:

if @var =~ /^string/ then
 ...
end


Ruby has you covered.

@var.start_with?('string')

As documented here: http://ruby-doc.org/core/classes/String.html#M001179


if @var =~ /^string/

The =~ indicates a regular expression match.

Alternatively you can do this:

if @var.include?("string")

but this means 'string' is anywhere in the string, not just at the beginning.


Try this:

if @var.start_with?("string")


'string'.match(/ring/i)

If you have a variable:

var = 'search'
'string'.match(/#{var}/i)

/i means case insensitive


You could use a regular expression (this one means that @var has to start with "string"):

if @var =~ /^string/


If you're planning on doing an ActiveRecord query with this,

SomeModel.where("column LIKE ?", "string%")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜