Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there something like 'with_indifferent_access' for arrays usable for include?

I try to only use :symbols for key words in my app. I try to strict decide between :symbol => logic or string => UI/language specific

But I get some "values" (ie. options and so on) per JSON, too, since there are no :symbols in JSON, all my invoked hashes have the "with_indifferent_access" attribute.

but: is there something equal for array? like that

a=['std','elliptic', :cubic].with_indifferent_access

a.include? :std => true

?

edit: added rails to tags

like image 885
halfbit Avatar asked Feb 16 '14 20:02

halfbit


2 Answers

a = ['std','elliptic', :cubic].map(&:to_sym)
a.include? :std
#=> true

Edit - regarding the comment by maxigs probably better to convert to strings:

a = ['std', 'elliptic', :cubic].map(&:to_s)
a.include? "std"
#=> true
like image 198
seph Avatar answered Oct 24 '22 02:10

seph


tl;dr

['std','elliptic', :cubic].flat_map { |s| [s.to_sym, s.to_s] }

Many times with Rails, I'll have a validation of inclusion in array. I, too, like to work with symbols. It might look something like this:

validates :source, inclusion: { in: [:source1, :source2] }

And that might be valid when I first create the object with a symbol, but becomes invalid when it reads source from the db and returns a string. I could monkey-patch the getters to always return symbols, but I'd rather not. Instead, I do:

validates :source, inclusion: { in: [:source1, :source2].flat_map { |s| [s, s.to_s] } }
like image 1
stevenspiel Avatar answered Oct 24 '22 04:10

stevenspiel