Take the 2-minute tour ×

I don't know Ruby but I'm having this problem with my application. Somebody can help me?

ActionView::TemplateError (can't convert nil into String) on line #7

4:  <h3><span><%= opinion.opinion %></span>: <%= opinion.keywords.sort.join(' / ').upcase %> </h3>
5:  <div class="original">Estado original: <span class="pos"><%= opinion.opinion %></span></div>
6:  <%#= highlight(simple_format(highlight_ontology(opinion)), opinion.keywords, :highlighter => '<em>\1</em>') %>
7:  <%= simple_format(highlight_ontology(opinion)) %>
8:  <%= button_to_remote('POSITIVO', {:url => url_for(opinion), :method => :put, :with => '"opinion[opinion]=POSITIVE"' }, :class => :positive) %>
9:  <%= button_to_remote('OBJETIVO', {:url => url_for(opinion), :method => :put, :with => '"opinion[opinion]=OBJECTIVE"' }, :class => :objective) %>
10: <%= button_to_remote('NEGATIVO', {:url => url_for(opinion), :method => :put, :with => '"opinion[opinion]=NEGATIVE"' }, :class => :negative) %>


share|improve this question
add comment

2 Answers

Using (variable || "") instead of just the variable should make it default to an empty string.

This technique is called null(or nil) coalescing.

share|improve this answer
depending on where the variable comes from, you might already want to default to "" before using it in the view. In your case that would probably be in highlight_ontology. –  trueunlessfalse Jan 13 '12 at 16:08
I prefer variable.to_s. –  sawa Jan 13 '12 at 18:49
Query: The error is "can't convert nil into String." How/why can you force the same variable to a string? –  adamwong246 Dec 27 '12 at 4:13
@adamwong246 I would question the opposite. Since NilClass defines to_s, why cant it convert to string? The answer is because it does not define to_str. This is why "#{nil}" works and "#{''+nil}" results in the above error –  Karthik T Aug 7 '13 at 9:39
tl:dr to_s does work –  Karthik T Aug 7 '13 at 9:43
add comment

Ruby does not automatically convert between data types. Some other scripting langagues do (perl, javascript) but ruby doesn't.

Why? To help you find errors earlier.

The thinking behind not converting nil to an string is: if this is nil, something went wrong. the programmer should know about this.

Dig deper into line 7 to find out where nil occurs!

share|improve this answer
add comment

Your Answer


