each_value raising NoMethodError [closed] - ruby

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have some model in which I have the following code:
appraisal_detail.each_value { |detail|
# some code...
}
It is raising NoMethodError with the message, "undefined method 'each_value'". Am I doing anything wrong? Any suggestions would be welcome.
Here is the full content of the method raising the error:
def self.update_appraisal_details(appraisal, appraisal_detail)
status = true
appraisal_detail_ids = appraisal.employee_appraisal_detail_ids
appraisal_detail.each_value { |detail|
appraisal_detail = find_by_employee_appraisal_id_and_kra_list_id(appraisal.id, detail[:kra_list_id])
if appraisal_detail.nil? # For newly added KRA
new_detail = EmployeeAppraisalDetail.new(detail.merge({:employee_appraisal_id => appraisal.id}))
status = (new_detail.save && status)
elsif appraisal_detail.status == "Inactive"
status = (appraisal_detail.update_attributes(:status => "Active") && status)
appraisal_detail_ids.delete(appraisal_detail.id)
else
appraisal_detail_ids.delete(appraisal_detail.id)
end
}
end

You should pass Hash object as appraisal_detail.
>> {1=>2}.each_value {|x| p x}
2
It seems like you are passing non-Hash object.
>> [].each_value { |x| p x }
NoMethodError: undefined method `each_value' for []:Array
from (irb):1
from /usr/bin/irb:12:in `<main>'

Related

create an instance for each element of an array ruby [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to create an instance of a class that each includes an element from the class's array. The array is like this
class CorporatePanel < ActiveRecord::Base
TEXT_ONLY = 'text only'
IMAGE_LEFT = 'image left'
IMAGE_RIGHT = 'image right'
IMAGE_ONLY = 'image only'
VIDEO = 'video'
PANEL_TYPE = [TEXT_ONLY, IMAGE_LEFT, IMAGE_RIGHT, IMAGE_ONLY, VIDEO]
So for each panel type i want an instance of the class corporate panel.
#corp_page = CorporatePage.create!(title: 'Home', static_descriptor: 'Home', workflow_state: 'draft')
#corp_panel = CorporatePanel::PANEL_TYPE
if #corp_page.title == 'Home'
puts "PAGE CREATED"
(#corp_panel.count).times do
corp_panel = CorporatePanel.new
#corp_panel.each do |x|
corp_panel.panel_type = x
end
if corp_panel.save
puts "#{corp_panel.title} created"
else
puts "#{corp_panel.title} not created"
puts corp_panel.errors.inspect
end
end
else
puts "Corp Page not saved"
puts #corp_page.inspect
end
So on every iteration through corporate panel it uses a different panel type. At the moment it creates five of each panel!
Thanks in Advance folks
Looking at the array documentation i found the method 'pop', to remove the last element of every array, seeing as this constant is an array, it worked.
corp_panel.panel_type = CorporatePanel::PANEL_TYPE.pop

Passing replacement string as parameter [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a code:
require 'pp'
def unquote_string(string)
if (string.is_a?(String))
string.gsub(/\\/,'')
else
string
end
end
def filter_array_with_substitution_and_replacement(array,options={})
pp options
return array unless %w(filterRegex substitudeRegex replacementExpression).any? {|key| options.has_key? key}
puts "I will substitude!"
filterRegex = options["filterRegex"]
substitudeRegex = options["substitudeRegex"]
replacementExpression = options["replacementExpression"]
pp "I have: #{replacementExpression}"
array.select{|object|
object =~ filterRegex
}.map!{|object|
object.sub!(substitudeRegex,unquote_string(replacementExpression))
}
end
def sixth_function
array = %w(onetwo onethree onefour onesix none any other)
filterRegex = /one/
substitudeRegex = /(one)(\w+)/
replacementExpression = '/#{$2}.|.#{$1}/'
options = {
"filterRegex" => filterRegex,
"substitudeRegex" => substitudeRegex,
"replacementExpression" => replacementExpression
}
filter_array_with_substitution_and_replacement(array,options)
pp array
end
def MainWork
sixth_function()
end
MainWork()
Output:
{"filterRegex"=>/one/,
"substitudeRegex"=>/(one)(\w+)/,
"replacementExpression"=>"/\#{$2}.|.\#{$1}/"}
I will substitude!
"I have: /\#{$2}.|.\#{$1}/"
smb192168164:Scripts mac$ ruby rubyFirst.rb
{"filterRegex"=>/one/,
"substitudeRegex"=>/(one)(\w+)/,
"replacementExpression"=>"/\#{$2}.|.\#{$1}/"}
I will substitude!
"I have: /\#{$2}.|.\#{$1}/"
["/\#{$2}.|.\#{$1}/",
"/\#{$2}.|.\#{$1}/",
"/\#{$2}.|.\#{$1}/",
"/\#{$2}.|.\#{$1}/",
"none",
"any",
"other"]
It is not correct, because string with replacement have metacharacters quoted. how to correct unquote this string replacementExpression?
Desired output for array after replacement:
["two.|.one/",
"three.|.one/",
"four.|.one/",
"six.|.one/",
"none",
"any",
"other"]
Forget unquote_string - you simply want your replacementExpression to be '\2.|.\1':
"onetwo".sub(/(one)(\w+)/, '\2.|.\1')
#=> "two.|.one"

Lambda returning different values [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm struggling with the following code:
I want a method to check if a string has content or not.
has_content = -> (a) { a!=nil && a.strip != ''}
c = ' '
has_content.call(c)
=> false
c.has_content
=> true
Why is the response different? Clearly I am lacking some Proc/lambdas knowledge.
I believe there is something missing in that code that is causing such behavior.
has_content is not defined for String, so unless you defined it before, it should raise an error
1.9.3p429 :002 > ''.has_content
NoMethodError: undefined method `has_content' for "":String
from (irb):2
from /Users/weppos/.rvm/rubies/ruby-1.9.3-p429/bin/irb:12:in `<main>'
As a side note, here's an alternative version of your code
has_content = ->(a) { !a.to_s.strip.empty? }
And here's an example
has_content.(nil)
# => false
has_content.('')
# => false
has_content.(' ')
# => false
has_content.('hello')
# => true

Code not working after little change [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm beginner in programming, I changed my code a little bit so that I can execute some def from the command line. After that change I got an error, but first my code:
require 'faraday'
#conn = Faraday.new 'https://zombost.de:8673/rest', :ssl => {:verify => false}
#uid = '8978'
def certificate
res = conn.get do |request|
request.url "acc/#{#uid}/cere"
end
end
def suchen(input)
#suche = input
#res = #conn.get do |request|
request.url "acc/?search=#{#suche}"
end
end
puts #res.body
Then I wrote into the console:
ruby prog.rb suchen(jumbo)
So, somehow i get the error:
Undefined method body for Nilclass
You're not invoking either of your methods, so #res is never assigned to.
#res evaluates to nil, so you're invoking nil.body.
RE: Your update:
ruby prog.rb suchen(jumbo)
That isn't how you invoke a method. You have to call it from within the source file. All you're doing is passing an argument to your script, which will be a simple string available in the ARGV array.
RE: Your comment:
It should go without saying that the solution is to actually invoke your method.
You can call the methods from the command line. Ruby has a function eval which evaluates a string. You can eval the command line argument strings.
Here's how. Change the line puts #res.body to
str = ARGV[1]
eval(ARGV[0])
puts #res.body
then run your program like so
$ ruby prog.rb suchen\(str\) jumbo

syntax error unexpected tIDENTIFIER [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I get the error message
syntax error, unexpected tIDENTIFIER, expecting ')'
leg = legislators_by_zipcode(zipcode)
when executing the code below:
require 'csv'
require 'sunlight/congress'
Sunlight::Congress.api_key = "c..."
def clean_zipcode(x)
x = x.to_s.rjust(5, "0")[0..4]
end
def legislators_by_zipcode(zipcode)
legislators = Sunlight::Congress::Legislator.by_zipcode(zipcode)
legislator_names = legislators.collect do |legislator|
"#{legislator.first_name} #{legislator.last_name}"
end
legislator_names.join(", ")
end
contents = CSV.open "event_attendees.csv", headers: true, header_converters: :symbol
contents.each do |row|
name = row[:first_name]
zipcode = clean_zipcode(row[:zipcode]
leg = legislators_by_zipcode(zipcode)
puts "#{name} #{zipcode} #{leg}"
You missed the closing brace()) here zipcode = clean_zipcode(row[:zipcode] in your code.Re write it as zipcode = clean_zipcode(row[:zipcode]).

Resources