Reputation: 1150
I have the following line of code in my model method.
subjectsinlist='['
subjectlist.subjects.each do |subject|
subjectsinlist=subjectsinlist+subject.subject_code+', '
end
subjectsinlist.chomp(', ')
subjectsinlist+="]"
An example of the strings to append are:
CPE205 CPE206 CPE301 CPE302 HW0210
I am expecting the results to hence be:
[CPE205, CPE206, CPE301, CPE302, HW0210]
But instead I am getting:
[CPE205, CPE206, CPE301, CPE302, HW0210, ]
The chomp
method does not seem to be working.
Any advice on why that happened would be appreciated.
Upvotes: 0
Views: 1986
Reputation: 54882
This can do the trick:
codes = "[#{subjectlist.subjects.map(&:subject_code).join(', ')}]"
Some explanations:
The map(&:subject_code)
will call the method subject_code
on each element of the array returned by subjectlist.subjects
The join(', ')
will put ', ' (coma-space) between each element of the array (except the last one).
The join
method is what you need here ;-)
Upvotes: 2
Reputation: 540
chomp returns a new string, see here
but u have to assign the new string to a variable:
subjectsinlist = subjectsinlist.chomp(', ')
Upvotes: 3
Reputation: 2469
subjectsinlist = '[' + subjectlist.subjects.join(', ') + ']'
That should work.
The reason chomp isn't working for you is because it returns a new string, rather than changing the existing string: http://apidock.com/ruby/String/chomp
Upvotes: 1