I've always used <%= some_code %>
to insert Ruby into HTML when using Ruby on Rails. I've just noticed that other projects sometimes use <%= some_code -%>
.

- 347,512
- 102
- 1,199
- 985

- 29,229
- 42
- 124
- 179
-
Superset question for all formats `<% %>` modifiers that came later: http://stackoverflow.com/questions/7996695/rails-erb-syntax – Ciro Santilli OurBigBook.com Sep 01 '14 at 21:09
-
@CiroSantilli: You're dominating these - nice work! I picked http://stackoverflow.com/questions/7996695/what-is-the-difference-between-and-in-erb-in-rails for this one, too... – Brad Werth Sep 02 '14 at 04:50
3 Answers
<%= some_code -%> The minus at the end removes the newline. Useful for formatting the generated HTML, while <%= some_code %> does not.
Thanks, Anubhaw

- 5,978
- 1
- 29
- 38
-
-
@ShawnSep `=` addes the output, `%` does not and is used for stuff like conditionals `<% if %>`. – Ciro Santilli OurBigBook.com Sep 01 '14 at 20:21
It's delete on Rails 3.
Now with Rails 3, there are no difference between this 2 forms.

- 46,608
- 11
- 99
- 105
-
Not sure where you read that, but -%> still stops ERB from producing a trailing newline in rails 3. – Samuel Sep 27 '10 at 13:24
-
According to the Rails 3 release notes: "You no longer need to place a minus sign at the end of a ruby interpolation inside an ERb template to remove the trailing carriage return in the HTML output." – coder_tim Sep 27 '10 at 18:35
-
1@Tim That means it will remove the trailing CR from your HTML output, not from every line. -%> still exists and is still useful. – Samuel Sep 28 '10 at 18:36
This answer was wrong: see https://stackoverflow.com/a/25617607/895245 instead.
In Ruby 2.1 (not necessarily with Rails), the -
removes one following newline as pointed by Anubhaw:
- the newline must be the first char after the
>
- no spaces are removed
- only a single newline is removed
- you must pass the
'-'
option to use it
Examples:
require 'erb'
ERB.new("<%= 'a' %>\nb").result == "a\nb" or raise
begin ERB.new("<%= 'a' -%>\nb").result; rescue SyntaxError ; else raise; end
ERB.new("<%= 'a' %>\nb" , nil, '-').result == "a\nb" or raise
ERB.new("<%= 'a' -%>\nb" , nil, '-').result == 'ab' or raise
ERB.new("<%= 'a' -%> \nb" , nil, '-').result == "a \nb" or raise
ERB.new("<%= 'a' -%>\n b" , nil, '-').result == 'a b' or raise
ERB.new("<%= 'a' -%>\n\nb", nil, '-').result == "a\nb" or raise
Doc: http://ruby-doc.org/stdlib-2.1.1/libdoc/erb/rdoc/ERB.html
Rails 4.1 appears to:
use ERB by default at: https://github.com/rails/rails/blob/fcbdac7e82725c388bf5adf56a9a9a16d4efdbe0/actionview/lib/action_view/template/handlers.rb#L10
set
-
by default at: https://github.com/rails/rails/blob/fcbdac7e82725c388bf5adf56a9a9a16d4efdbe0/actionview/lib/action_view/template/handlers/erb.rb#L77

- 1
- 1

- 347,512
- 102
- 1,199
- 985