0

my table has Attachment.attachment_content_type which is of type string. Values look like this:

[]
[image/png]
[application/msword, application/word, application/x-msword, application/x-word, text/plain]

What I want to do is get the first item if any.

I'm trying with:

attachment.attachment_content_type[0]

But that just returns [ and not 'application/msword'

Should I use a split or is there a better way with ruby on rails to tell rails this is an array? Thanks

2
  • The answers below are correct solutions. I'm a little curious about why these are being stored in a somewhat difficult-to-parse string. If you control the code, consider using ActiveRecord's serialize to store/retrieve a real Ruby array, or consider creating a has_many relationship to another table (probably overkill for this). Commented Dec 5, 2012 at 21:25
  • This is being done by rails paperclip gem Commented Dec 5, 2012 at 21:26

3 Answers 3

3
$ cat foo.rb 

strings = [
  "[]",
  "[image/png]",
  "[application/msword, application/word, application/x-msword, application/x-word, text/plain]"
]

strings.each do |string|
  array = string[1...-1].split(/[\s,]+/)
  puts array[0]
end

$ ruby foo.rb 

image/png
application/msword
Sign up to request clarification or add additional context in comments.

1 Comment

By way of explanation for Rachel, the value "[]" and others are Strings, so must be parsed and turned into arrays.
1

attachment.attachment_content_type[1..-2].split(',').map(&:strip) will return the contents of the string as an array.

Comments

0

Try using gsub! and scan.

mimetypes.gsub!(/([\[\]])/, '')
mime_array = mimetypes.scan(/, /)

See the String API for more interesting methods along with Rubular for regex testing :)

Comments

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.