0

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

params[:abc]         # => "neon green"
@abc                 # => ["neon green"]  
params[:abc] == @abc # => false
2
  • Your question is not clear. You are already successfully comparing them by ==. What is wrong with it? Commented Mar 15, 2015 at 6:05
  • You cannot compare Array with String, the type is unconsistent here, you should precise what you want to do exactly. Commented Mar 15, 2015 at 6:18

5 Answers 5

3

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) # => []
Sign up to request clarification or add additional context in comments.

Comments

1

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] # => []

Comments

1

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

3 Comments

yea looks more elegant and neat. Thanks Mohammad!
No mohammad. this is not working. [@abc] => [["neon green"]] [5] pry(#<AbcController>)> params[:abc].first => "n"
ah ok, i swapped the types, well you get the idea.
0

I'd do:

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

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

Comments

0

Try this

params[:abc].in? @abc

1 Comment

in? is a rails method, not a core-ruby method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.