Ruby function with an if statement - ruby

I have this following function but somehow it doesn't get inside the if statement. This is my gist on line 68
I'm trying to evaluate if an object.country name has the same name as "example_of_a_country_name"
def find_population_of_country(liste_pays, country_name)
given_country_population = 0
liste_pays.each do |n|
if (n.country.eql?(country_name.upcase))
given_country_population = n.population
#I'm trying to see if it's output something here
puts country_name.upcase
end
return given_country_population
end
end

can you type this within your function and tell me what you get?:
def find_population_of_country(liste_pays, country_name)
liste_pays.select {|n| n.country.eql?(country_name.upcase) }
end
end

The problem is your line:
return given_country_population
This should be moved one line up, inside the if ... end block for the name comparison, otherwise, it's returning even for non-matches.

Related

`initialize': wrong number of arguments (given 0, expected 2) (ArgumentError)

class LineAnalyzer
##highest_wf_count=[]
##highest_wf_words=[]
attr_accessor :highest_wf_count ,:highest_wf_words ,:content , :line_number
def initialize(line,num)
#content=line
#line_number=num
calculate_word_frequency(#content,#line_number).call
end
def calculate_word_frequency(con,num)
#content,#line_number=con,num
#arr= #content.split()
#arr.map do |txt|
#count=0
#i=0
while #i<#content.length
#count+=1 if txt.eql?(#arr[#i])
#i+=1
end
##highest_wf_count[#line_number]= #count
##highest_wf_words[#line_number]= txt
#arr.delete(txt)
end
end
end
class Solution < LineAnalyzer
attr_accessor :analyzers, :highest_count_across_lines, :highest_count_words_across_lines
def initialize
#analyzer=[]
#highest_count_across_lines=0
#highest_count_words_across_lines=[]
end
def analyze_file()
#arr=IO.readlines(ARGV[0])
#analyzers=Array.new(#arr.length){LineAnalyzer.new}
#i=0
#analyzer.each do |obj|
obj(#arr[#i],#i)
#i+=1
end
end
def calculate_line_with_highest_frequency()
#highest_count_across_lines = ##higest_wf_count.max
#i=0
##highest_wf_count.each do |count|
#highest_count_words_across_lines.push ##highest_wf_words[#i] if count==#highest_count_across_lines
#i+=1
end
end
The above code is to calculate word frequency in a text file
Whenever I try to run this below command I get the following error int the intialize function in LineAnalyzer class
ruby module2_assignment.rb test.txt
Error : `initialize': wrong number of arguments (given 0, expected 2) (ArgumentError)
Since I am a beginner in Ruby I can't figure out the error.
The issue is in this line
#analyzers=Array.new(#arr.length){LineAnalyzer.new}
LineAnalyzer's constructor requires two parameters, you're passing none
well, the issue of initialize: wrong number of arguments can be resolved in passed arguments into LineAnalyzer.new, but we still have broken script after those changes, so, as I see, this script in [WIP] status, and we need to make some more changes to make it works.
If you can share more details about the goal of analyzing here, it would be nice.
so, go to code, we need to remove call from this line:
calculate_word_frequency(#content,#line_number)
and fix initializer logic here:
def initialize
#analyzers=[]
#highest_count_across_lines=0
#highest_count_words_across_lines=[]
end
def analyze_file()
#arr=IO.readlines(ARGV[0])
#i=0
#arr.each do |line|
#analyzers << LineAnalyzer.new(line,#i)
#i+=1
end
end
btw you have a typo in this line:
#highest_count_across_lines = ##higest_wf_count.max
should be:
#highest_count_across_lines = ##highest_wf_count.max
so, we've resolved issue, but it still not good, coz output is nothing:
ruby module2_assignment.rb test.txt
Test text
Test text
Test text
1
1
1
coz should be something like this:
module2_assignment.rb test.txt
1
2
3
"The following words have the highest word frequency per line: "
"[\"test\", \"text\"] (appears in line 1)"
"[\"test\", \"text\"] (appears in line 2)"
"[\"test\", \"text\"] (appears in line 3)"
So, I think we have 2 options here:
invest some more efforts to make it works
try to find a similar solution
we can use this worked solution of module2_assignment, for example:
https://github.com/zbristor/rubyWordFrequency/blob/2417324381378f6be76485f6271465cd641ec0ff/module2_assignment.rb
I hope it's help

.include? is not triggered when reading a txt file

I am under the impression that the following code should return either the search item word or the message no match - as indicated by the ternary operator. I can't diagnose where/why include? method doesn't work.
class Foo
def initialize(word)
#word=word
end
def file_open
IO.foreach('some_file.txt') do |line|
line.include?(#word) ? "#{#word}" : "no match"
end
end
end
print "search for: "
input = gets.chomp.downcase
x = Foo.new(input)
puts x.file_open
The input exists in some_file.txt. My ternary operator syntax is also correct. IO reads the text fine (I also tried File.open() and had the same problem). So I must be making a mistake with my include? method.
You need to control the returned value. file_open defined above will always return nil. The ternary will be executed properly, but nothing is done with its value. Instead you can do the following:
class Foo
def initialize(word)
#word=word
end
def file_open
IO.foreach('some_file.txt') do |line|
return line if line.include?(#word)
end
return "no match"
end
end

How to stop outer block from inner block

I try to implement search function which looks for occurrence for particular keyword, but if --max options is provided it will print only some particular number of lines.
def search_in_file(path_to_file, keyword)
seen = false
File::open(path_to_file) do |f|
f.each_with_index do |line, i|
if line.include? keyword
# print path to file before only if there occurence of keyword in a file
unless seen
puts path_to_file.to_s.blue
seen = true
end
# print colored line
puts "#{i+1}:".bold.gray + "#{line}".sub(keyword, keyword.bg_red)
break if i == #opt[:max] # PROBLEM WITH THIS!!!
end
end
end
puts "" if seen
end
I try to use break statement, but when it's within if ... end block I can't break out from outer each_with_index block.
If I move break outside if ... end it works, but it's not what I want.
How I can deal with this?
Thanks in advance.
I'm not sure how to implement it in your code as I'm still learning Ruby, but you can try catch and throw to solve this.
def search_in_file(path_to_file, keyword)
seen = false
catch :limit_reached do
#put your code to look in file here...
throw :limit_reached if i == #opt[:max] #this will break and take you to the end of catch block
Something like this already exist here

Return doesn't output the method to the console

When I call the greeter method, it doesn't output the string to the console. I'm having a hard time understanding why. Can anyone help?
def greeter(name)
return "Hello #{name}!!"
end
def by_three?(num)
if num % 3 == 0
puts true
else
puts false
end
end
greeter("Michael")
by_three?(4)
return returns value from method, but doesn't print it. You need:
puts greeter("Michael")
Also you don't need this return, at all, method returns value of the last executed line.

Undefined method in console?

Here comes another Codecademy question:
The following challenge has been presented.
Define two methods in the editor:
A greeter method that takes a single string parameter, name, and
returns a string greeting that person. (Make sure to use return and
don't use print or puts.)
A by_three? method that takes a single integer parameter, number, and
returns true if that number is evenly divisible by three and false if
not. Remember, it's a Ruby best practice to end method names that
produce boolean values with a question mark.
The code I put in re: was..
def greeter(name)
return "Greet #{name}"
end
def by_three?(x)
if x % 3==0
returns true
else
return false
end
greeter("Brant")
by_three?(6)
The console then gives me the following error:
Did you define your greeter method?
It seems like I have. Am I wrong?
this would be it:
def greeter(name)
"Greet #{name}"
end
def by_three?(x)
x % 3 == 0
end
greeter("Brant") # => "Greet Brant"
by_three?(6) # => true
It looks like you did not add "end" after your else statement. Here you go.
#For the greeter method, i decided to use this format
def greeter(name)
return name
end
greeter("Hello Jane, good morning")
def by_three?(number)
if number % 3 != 1
return true
else
return false
end #Add end here to end your statement
end
by_three?(5)

Resources