Trying to truncate a string in Ruby/Sinatra in an .erb page.
I have been trying variants of:
<%= #caption_str.truncate(20) %>
<%= #caption_str[0..20] %>
But keep getting error messages of the kind:
NoMethodError at /392471267473009
undefined method `[]' for nil:NilClass
or
NoMethodError at /392471267473009
undefined method `truncate' for nil:NilClass
All is well if I don't truncate the string, i.e.
<%= #caption_str %>
What am I missing?
NoMethodError at /392471267473009
undefined method `[]' for nil:NilClass
or
NoMethodError at /392471267473009
undefined method `truncate' for nil:NilClass
The errors are descriptive enough.
They convey that there is no [] or truncate method defined for nil:NilClass, which in this case turns out to be your #caption_str object.
Check if #caption_str is not nil and then do these operations. When #caption_str would be nil, you'll get the same error.
Since, Ruby is a dynamic programming language, we tend to forget the edge-cases when the values would be nil. Always include checks when similar situations arise.
Related
I'd like to make some modifications on variable in erb templates:
e.g. decode base64 and split string
It tried
<%= Base64.decode64(#my_variable).rpartition(':').last %>
and
<%= Base64.decode64(<%= #my_variable %>).rpartition(':').last %>
and via scope
<%= Base64.decode64(scope['my_class::my_variable']).rpartition(':').last %>
but it is nil.
Filepath: /usr/lib/ruby/1.9.1/base64.rb
Line: 58
Detail: undefined method `unpack' for nil:NilClass
puppet version 3.8.2
The first example that you tried is the correct ERB notation.
That error would be occurring because you passed the nil object to Base64.decode64():
[1] pry(main)> require 'base64'
=> true
[2] pry(main)> Base64.decode64(nil).rpartition(':').last
NoMethodError: undefined method `unpack' for nil:NilClass
from /Users/alexharvey/.rvm/rubies/ruby-2.1.4/lib/ruby/2.1.0/base64.rb:58:in `decode64'
(Admittedly, I don't have your Ruby 1.9.1 and I wasn't able to easily install it, but it's unlikely this changed.)
That means that #my_variable is set to nil, and that would happen if you failed to actually set the Puppet variable $my_variable in your manifest.
So you would need to call the template with a block something like this:
$my_variable = 'foo'
file { '/tmp/foo':
ensure => file,
content => template('test/mytemplate.erb')
}
Does anyone know what I'm doing wrong here, I installed Ruby 2.1, Sequel-4.26.0 gem and mislav-will_paginate-2.3.10 gem, but when i try to use the paginate function, i keep getting the following error:
Code:
#user = User.paginate(:page => 1, :per_page => 2)
Error message:
"ERROR: NoMethodError: undefined method `paginate' for #"
Most likely paginate is a dataset method, not a class method (this is true for Sequel's pagination extension, not sure about will_paginate). If you want User.paginate to work:
def User.paginate(*args)
dataset.paginate(*args)
end
Dear stackoverflow community,
Beginner's question:
Why do I get the following error?
scraper_sample_2.rb:7:in `<main>': undefined method `[]' for nil:NilClass (NoMethodError)
>Exit code: 1
Here's my code (copied from a ruby's intro guide):
require "rubygems"
require "crack"
require "open-uri"
URL = "http://www.recovery.gov/pages/GetXmlData.aspx?data=recipientHomeMap"
Crack::XML.parse(open(URL).read)["totals"]["state"].each do |state|
puts ["id", "awarded", "received", "jobs"].map{|f| state[f]}.join(",")
end
Because Crack::XML.parse(open(URL).read)["totals"] is nil. Try to split the call you do on line 7 on several lines and debug each call separately. Maybe the answer you get is not what you expect.
Given the format of the xml returned from your source, Crack::XML.parse(open(URL).read)["totals"] will, as Ivaylo said, return nil. The format of the xml must have changed, as totals are now within /map/view.
To get the expected output, change your code to:
Crack::XML.parse(open(URL).read)["map"]["view"]["totals"]["state"].each do |state|
puts ["id", "awarded", "received", "jobs"].map{|f| state[f]}.join(",")
end
A basic code in ruby that isn't working for me.... The error specifies
NoMethodError (undefined method `to_i' for
row = row.split(",").map { |x| x.to_i }
EDIT:
NoMethodError (undefined method `to_i' for [["123,123,123,"]]:Array):
app/controllers/sessions_controller.rb:21:in `import'
app/controllers/sessions_controller.rb:20:in `each'
app/controllers/sessions_controller.rb:20:in `import'
app/controllers/sessions_controller.rb:17:in `each'
app/controllers/sessions_controller.rb:17:in `import'
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.7ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (8.2ms)
you're receiving that error because you're calling the method .to_i on an array, which is wrong since that method is of the String class, source :http://www.ruby-doc.org/core-2.1.0/String.html#method-i-to_i
So in order to fix this we need to take that string from the array so we can turn it into an integer, remember that you started with an array containing an array, so that's why I'm calling .pop twice:
row = [["123, 123, 123"]]
string_of_numbers = row.pop.pop
string_of_numbers.split(",").map {|x| x.to_i }
If it feels too odd try to play with it on irb, that's usually how I try to sort these kinds of things out, don't forget to always refer to the official documentation
I am new to Rails (using 3.2.9) and get a NoMethodError I don't know how to fix. Can anyone help, please?
A NoMethodError occurred in trade_plans#update:
undefined method `[]' for false:FalseClass
app/models/trade_plan.rb:96:in `symbol_is_valid'
And this is line 96 in trade_plan.rb:
if(data[:last_trade_price_only] == "N/A" || data[:last_trade_price_only].blank?)
Any ideas why this error occurs and how to fix it?
Thanks :)
That's probably because your local variable data has the value false instead of being an instance of Hash.
Since you are trying to call the method [] on the object false, it raises a NoMethodError because false does not respond to [].