title: How to return a value or conditionally raise an error in Ruby?
body: <p>I am calling an API from a Rails model and I would like to raise an error if the API returns on non-200 code. Otherwise I want to cache/lazy-load the data. This is my method:</p>
  
  <pre><code>def data
      @data ||= SNL.get_list(name)
      raise StandardError, @data.inspect unless @data.success?
      @data
  end
  </code></pre>
  
  <p>This works but I was wondering if I can accomplish this in one line. I tried using the <code>and</code> operator combined with an <code>unless</code> but couldn't get it to work.</p>
  
  <p>Update: I have accepted tokland's answer because I asked for one line and he/she provided two very good solutions. In the end I am actually going to use</p>
  
  <pre><code>def data
    @data ||= SNL.get_list(name)
    @data.success? ? @data : (raise StandardError, @data.inspect)
  end
  </code></pre>
  
  <p>for readability. I just hated having a third line just to return <code>@data</code>, since an exception will rarely be raised. I feel odiszapc's answer is a the best compromise of brevity and readability. Thanks everyone.</p>