user2511030
user2511030

Reputation: 515

Comparing a string with an array

How do I compare "string1" with ["string1"]? The following results in false:

params[:abc]         # => "neon green"
@abc                 # => ["neon green"]  
params[:abc] == @abc # => false

Upvotes: 0

Views: 71

Answers (5)

Mohammad AbuShady
Mohammad AbuShady

Reputation: 42909

you can wrap the second one in an array, or extract the string from the array

[params[:abc]] == @abc

or

params[:abc] == @abc.first

I kinda like the first one more

Upvotes: 1

Uri Agassi
Uri Agassi

Reputation: 37419

Another option - put the string inside an array of itself:

[params[:abc]] == @abc # => true

Or, if you don't know which one is an array, use an array-splat ([*]) combination:

[*params[:abc]] == [*@abc] # => true

Array-splat will work in a similar fashion to @Jkarayusuf's Array():

[*["string1"]] # => ["string1"]
[*"string1"] # => ["string1"]
[*nil] # => []

Upvotes: 1

Jkarayusuf
Jkarayusuf

Reputation: 361

You could use Array#include?. However, this will return true if the array contains "string1" and "string2".

["string1"].include?("string1")            # => true
["string1", "string2"].include?("string1") # => true

In the event you want to compare the array contains only the string, I'd recommend using the Array method, which converts the parameters provided to it into an array.

Array(["string1"]) == Array("string1")            # => true
Array(["string1", "string2"]) == Array("string1") # => false

How it works:

Array(["string1"]) # => ["string1"]
Array("string1") # => ["string1"]
Array(nil) # => []

Upvotes: 3

pkrawat1
pkrawat1

Reputation: 681

Try this

params[:abc].in? @abc

Upvotes: 0

Sharvy Ahmed
Sharvy Ahmed

Reputation: 7405

I'd do:

@abc = @abc.join('')
#=> "neon green"

if params[:abc] == @abc
   do thing 1
else
   do thing 2
end

Upvotes: 0

Related Questions