Search code examples
ruby-on-railsrubyhaml

What is the difference between = and - in haml while writing ruby code?


So I am a newbie at HAML.

While going through the HAML tutorial the way to represent ruby code was mentioned as =

eg: %strong= item.title

but when I ran this code:

= @list.documents.each do |doc|
  %tbody
    %tr
      %td= doc.display_name

along with all the list data which was displayed there was also alot of junk data displayed which was related to the actual list data which was displayed. This is what I got:

val1 val2 val3 [#Document......@id : val1, @id:val2.....]

When i try the same code while replacing the = with a - the unwanted data is not received.

- @list.documents.each do |doc|
      %tbody
        %tr
          %td= doc.display_name

output:

val1 val2 val3

can someone explain the difference between - and = while writing ruby code in haml?


Solution

  • They are both indicators that what follows needs to be processed as Ruby code. But - doesn't output the result to view whereas = does.

    For example, consider the following helper:

    def hlp
      [1,2].each(&:succ) # using example relevant to your code sample
    end
    

    each will return the enumerator that it is called upon. So the return value of that helper method will be [1,2].

    The following in your HAML view will not display [1,2]:

    - hlp
    

    But the following will display it:

    = hlp
    

    Therefore in the sample code you have shared, you will use -, and not =, because you don't want to display all @list.documents once each is done with them.