18

I'm trying to write a single line if else statement in a view.

<%= collection.name ? collection.name : @miniature.name %>

I want it to put collection.name if one exists, otherwise I want it to put @miniature.name

Ossie
  • 1,103
  • 2
  • 13
  • 31

3 Answers3

32

To make it even clearer, you can use logical OR and ActiveSupport's Object#presence (to put collection.name only if it exists and isn't blank):

<%= collection.name.presence || @miniature.name %>

If you want to display collection.name if it's not nil, but it's blank (empty string or string containing only whitespace), it will be enough to have:

<%= collection.name || @miniature.name %>
Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
30

Check for the presence of collection.name first.

<%= collection.name.present? ? collection.name : @miniature.name %>
davegson
  • 8,205
  • 4
  • 51
  • 71
0

Couldn't you have

<%= collection.name ||= @minature.name %>

To those who downvoted - Set Ruby variable if it is not already defined

Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147
  • Sorry I was writing as a conversation - let me change – Richard Peck Mar 26 '14 at 15:21
  • 2
    I don't understand. This won't do what OP expects (display `collection.name` or `@miniature.name`) but will do what OP doesn't expect (set `collection.name` to `@miniature.name` if `@collection.name` is `nil`). – Marek Lipka Mar 26 '14 at 15:23
  • I believe my answer provided a valid answer to the OP – Richard Peck Mar 26 '14 at 15:31
  • 1
    Your edited answer is valid, but it still may be surprise to OP that it also SETS `collection.name` to `@miniature.name` if it's `nil`. OP didn't specify this in requirements. Of course, I know the meaning of `||=` syntax, but I think it's not relevant here. – Marek Lipka Mar 26 '14 at 15:32