Sorting array with multiple variables - ruby

I am trying to create a program where by the user can enter multiple names. those names are then displayed under each other in alphabetical order, and print(display) every second name backwards. i have gone through several tutorials this is my second day using ruby.. here is what i have so far.
name_list = {}
puts 'please enter names seperated by a space:'
name_list = gets.chomp
names = name_list.split(" ")
to grab names...
names.sort do |a,b| a.upcase <=> b.upcase end
display = "#{names}"
for ss in 0...display.length
print ss, ": ", display[ss], "\n"
end
to arrange them alphabetically and under each other.
i am really struggling to mesh it all together i think i have got at least half a dozen errors in here...if i am on the wrong path could someone guide me to some info so i can start again??
EDIT
i also had this idea of using a class.
but i would have to program the names in i wanted the user to be able to add info via the consol.
class A
def initialize(name)
#name = name
end
def to_s
#name.reverse
end
end
>> a = [A.new("greg"),A.new("pete"),A.new("paul")]
>> puts a

Problems in your code:
name_list defined as an empty hash at the top but not used.
split(" ") -> split
sort { |a, b| a.method <=> b.method } -> sort_by { |x| x.method } -> sort_by(&:method)
sort is not an in-place operation, assign the result (or directly use it).
display = "#{names}" -> display = names
for ss in 0...display.length -> enumerable.each_with_index { |item, index| ... }
don't write do/end in one-liners, use { ... }
I'd write:
puts 'Please enter names separated by spaces'
gets.split.sort_by(&:upcase).each_with_index do |name, index|
puts "%s: %s" % [index, (index % 2).zero? ? name : name.reverse]
end

A few pointers then:
names.sort do |a,b| a.upcase <=> b.upcase end # Will not modify the "names" array, but will return a sorted array.
names.sort! do |a,b| a.upcase <=> b.upcase end # Will modify the "names" array.
To display your names:
names.each_with_index do |name, index|
if index % 2 == 0
puts name
else
puts name.reverse
end
end

puts 'please enter names seperated by a space`enter code here` :'
names = gets.chomp.split(" ")
names.sort! {|a,b| a.upcase <=> b.upcase } # For a single line use {..} instead of do..end
names.each_with_index do |n,i|
if i % 2 == 0
p n
else
p n.reverse
end
end
You can also use a ternary operator, I used the full if else block for readability in this case.
names.each_with_index do |n,i|
p (i % 2 == 0) ? n : n.reverse
end
EDIT
command = ""
names = []
while command != "exit"
puts 'please enter names seperated by a space`enter code here` :'
command = gets.chomp!
if command == "display"
names.sort! {|a,b| a.upcase <=> b.upcase } # For a single line use {..} instead of do..end
names.each_with_index do |n,i|
if i % 2 == 0
p n
else
p n.reverse
end
end
else
names << command
end
end

Related

Any way to optimize this character counter i wrote in ruby for String class

# Character Counter
class String
def count_lcases
count(('a'..'z').to_a.join(''))
end
def count_upcases
count(('A'..'Z').to_a.join(''))
end
def count_num
count((0..9).to_a.join(''))
end
def count_spl_chars
length - count_lcases - count_upcases - count_num
end
end
input = ARGV[0]
if ARGV.empty?
puts 'Please provide an input'
exit
end
puts 'Lowercase characters = %d' % [input.count_lcases]
puts 'Uppercase characters = %d' % [input.count_upcases]
puts 'Numeric characters = %d' % [input.count_num]
puts 'Special characters = %d' % [input.count_spl_chars]
I used ranges to count characters but count function is called 3 times.
I can always use loops and count it one by one.I was wondering is there any way to optimize this?...
If you are using Ruby 2.7 you could use tally; the string's chars are just iterated one time.
def classify_char(c)
case c
when /[a-z]/ then :lcase
when /[A-Z]/ then :ucase
when /\d/ then :digit
else :other
end
end
p "asg3456 ERTYaeth".chars.map{|c| classify_char(c) }.tally
# => {:lcase=>7, :digit=>4, :other=>2, :ucase=>4}
If Ruby 2.3...2.7, this will work:
CHAR_CLASSES = {
lcase: ?a..?z,
ucase: ?A..?Z,
digit: ?0..?9,
}
p "asg3456 ERTYaeth".each_char.with_object(Hash.new(0)) { |c, o|
o[CHAR_CLASSES.find { |label, group| group === c }&.first || :other] += 1
}
For < 2.3,
p "asg3456 ERTYaeth".each_char.with_object(Hash.new(0)) { |c, o|
p = CHAR_CLASSES.find { |label, group| group === c }
o[p ? p.first : :other] += 1
}

Delete an array from a class in ruby

So I am creating a class in ruby where in I will be able to insert my data on a text file and then read, find from it but I am stuck on delete as well update/edit.
Basically I created a method called "find" and I made it as a reference on my "delete" method.
def find(keyword="")
if keyword
person = People.read_people
found = person.select do |pip|
pip.name.downcase.include?(keyword.downcase) ||
pip.age.downcase.include?(keyword.downcase) ||
pip.country.downcase.include?(keyword.downcase)
end
found.each do |person|
puts person.name + " | " + person.age + " | " + person.country
end
else
puts "find using a key phrase eg. 'find sam' \n\n"
end
end
def list
puts "\nListing People \n\n".upcase
people = People.read_people
people.each do |person|
puts person.name + " | " + person.age + " | " + person.country
end
end
def delete(keyword="")
if keyword
person = People.read_people
found = person.select do |pip|
pip.name.downcase.include?(keyword.downcase) ||
pip.age.downcase.include?(keyword.downcase) ||
pip.country.downcase.include?(keyword.downcase)
end
person.delete(found)
else
puts "find using a key phrase eg. 'find josh' \n\n"
end
end
As you can see I was trying to delete the supplied keyword from the array (w/c was save on a text file) via class method called read_people. Here's how it looks like:
def self.read_people
# read the people file
# return instances of people
people = []
if file_usable?
file = File.new(##filepath, 'r')
file.each_line do |line|
people << People.new.import_line(line.chomp)
end
file.close
end
return people
end
def import_line(line)
line_array = line.split("\t")
#name, #age, #country = line_array
return self
end
How can I fix this and delete the found item via keyword?
See the actual codes here: https://repl.it/repls/VastWildFact
Change
person.delete(found)
to
person -= found # Equivalent to person = person - found
It should work as per https://ruby-doc.org/core-2.2.0/Array.html#method-i-2D
ary - other_ary → new_ary
Returns a new array that is a copy of the original array, removing any items that also appear in other_ary. The order is preserved from the original array.
It compares elements using their hash and eql? methods for efficiency.
Example: [ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ] #=> [ 3, 3, 5 ]
Another solution is to use reject as follows:
person.reject! do |pip|
pip.name.downcase.include?(keyword.downcase) ||
pip.age.downcase.include?(keyword.downcase) ||
pip.country.downcase.include?(keyword.downcase)
end
Basically you're going to want an export_people and write_people method that'll look something like this:
def self.export_people(people)
people.map do |person|
[person.name, person.age, person.country].join("\t")
end
end
def self.write_people(people)
File.new(##filepath, 'w') do |f|
f.write(export_people(people))
end
end
# Usage:
Person.write_people(array_of_people)
With the above code, you'd call the modified delete method as detailed in Tarek's answer, and then Person.write_people(array_of_people) to write back to the file.

Word Count returns an array (of arrays of the form [word, count]) representing the frequency of each word

str = 'put returns between paragraph put returns between paragraph put returns between paragraph'
def word_count(string)
resut= []
return result = string.split.inject(Hash.new(0)) { |h,v| h[v] += 1; h }
end
def parse_word(word)
word.gsub!(/[^a-zA-Z0-9]/, " ")
word.downcase!
#yoo= word
end
result =word_count(str)
print result, "\n\n"
res2 = result.select { |pair| pair[1] > 1 } `#Error coming`
I am getting OutPut
**
OutPut
**
{"put"=>3, "returns"=>3, "between"=>3, "paragraph"=>3}
I need OutPut Like this
**
OutPut
**
{"put"=>3, "returns"=>3, "between"=>3, "paragraph"=>3}
and
put: 3
returns: 3
between: 3
but the main problem is that he gave us the code to do that but i cant able to understand it
I am not getting this what this code will do can anyone help me ...And modify it so it can work
The following processes the first paragraph of put returns ... Note that ss is an array of those words that occur at least twice in this paragraph.
nect = ss.select { |p| p[1] > 1 }
nect .sort.each do |key, count|
puts "#{key}: #{count}"
end
module WordCount
def self.word_count(s)
count_frequency(words_from_string(s))
end
def self.word_count_from_file(filename)
s = File.open(filename) { |file| file.read }
word_count(s)
end
def self.words_from_string(s)
s.downcase.scan(/[\w']+/)
end
def self.count_frequency(words)
counts = Hash.new(0)
for word in words
counts[word] += 1
end
# counts.to_a.sort {|a,b| b[1] <=> a[1]}
# sort by decreasing count, then lexicographically
counts.to_a.sort do |a,b|
[b[1],a[0]] <=> [a[1],b[0]]
end
end
end
def word_count(s)
WordCount.word_count(s)
end

Ruby: Method return without a block

I am trying to make this code return when called without a block. The uncommented lines at the bottom is what I'm trying to get to return. The first uncommented line should return in tut, second line converted to english and the last should be in english. And why is the line " puts eng " returning up and down and not in sentence form? Thanks for any and all help.
Here's my code:
class Tut
##consonants = ["b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z"]
def is_tut? string
if string =~ /^(([b-df-hj-np-z]ut)|([aeiou\s])|[[:punct:]])+$/i
yield
else
false
end
end
def self.to_tut string
string.each_char do |c|
c += "ut" if ##consonants.find { |i| i == c.downcase }
yield c if block_given?
end
end
def self.to_english string
array = string.split //
array.each do |c|
if ##consonants.find { |i| i == c.downcase }
array.shift
array.shift
end
yield c if block_given?
end
end
end
#Tut.to_tut( "Wow! Look at this get converted to Tut!" ) { |c| print c }
# should output : Wutowut! Lutookut atut tuthutisut gutetut cutonutvuteruttutedut tuto Tututut!
#puts
#puts
tut = Tut.to_tut( "Wow! Look at this get converted to Tut!" )
puts "from return: #{tut}"
puts
#Tut.to_tut( "Wutowut! Lutookut atut tuthutisut gutetut cutonutvuteruttutedut tuto Tututut!" ) { |c| print c }
#should outout : Wutowut! Lutookut atut tuthutisut gutetut cutonutvuteruttutedut tuto Tututut!
#puts
#puts
tut = Tut.to_tut( "Wutowut! Lutookut atut tuthutisut gutetut cutonutvuteruttutedut tuto Tututut!" )
puts "from return: #{tut}"
#puts
#tut_string = ""
#Tut.to_tut( "I'm in tut but I want to be in english." ) { |c| tut_string += c }
#puts tut_string
# should output : I'mut inut tututut bututut I wutanuttut tuto bute inut enutgutlutisuthut.
puts
#Tut.to_english( tut_string ){ |c| print c }
# should output : I'm in tut but I want to be in english.
lan = Tut.to_english( tut )
puts lan
(Opening note: You normally don't want to modify an Enumerable object while iterating over it, since that makes it much harder to read the code and debug it.)
Your to_tut doesn't retain your modifications because the "c" block variable is a copy of the string slice, instead of a reference to part of the string (if it were a ref, you'd be able to use << to append; "+=" still wouldn't work because it reassigns rather than changing the ref). That's just how each_char works, since a String doesn't contain references.
If you wanted to modify the string in place, you'd probably have to count backwards and then insert the 'ut' by index via string#[]= . But that's way complicated so I'll present a couple alternates.
Working to_tut #1:
def self.to_tut string
string.chars.map do |c|
yield c if block_given?
# this must be the last expression the block
if ##consonants.find { |i| i == c.downcase }
c + 'ut'
else
c
end
end.join
end
Working to_tut #2 - this is probably the most ruby-ish way to do it:
def self.to_tut string
string.gsub(/[#{##consonants.join}]/i) {|match|
yield match if block_given?
# this must be the last expression in the block
match + 'ut'
}
end
Your to_english doesn't work because array.shift always removes the first element of the array. Instead, you want to track the current index, and remove 2 chars starting from index+1.
Working to_english:
def self.to_english2 string
array = string.split //
array.each_with_index do |c, idx|
if ##consonants.find { |i| i == c.downcase }
array.slice!(idx+1, 2)
end
yield c if block_given?
end
array.join
end
Regarding why your "puts lan" returns one char per line - it's because your to_english returns an array. You'll want to call join to convert it.
The methods to_tut and to_english are giving you wrong answers when used without a block. This happens because ruby always returns the last value evaluated in your method. In your code that will be the result of the string.each_char for to_tut or array.each for to_english. In both cases, the result contains the original input, which is consequently returned and printed.
As to the puts eng, it prints the array returned by array.each of to_english.

Recursively merge multidimensional arrays, hashes and symbols

I need a chunk of Ruby code to combine an array of contents like such:
[{:dim_location=>[{:dim_city=>:dim_state}]},
:dim_marital_status,
{:dim_location=>[:dim_zip, :dim_business]}]
into:
[{:dim_location => [:dim_business, {:dim_city=>:dim_state}, :dim_zip]},
:dim_marital_status]
It needs to support an arbitrary level of depth, though the depth will rarely be beyond 8 levels deep.
Revised after comment:
source = [{:dim_location=>[{:dim_city=>:dim_state}]}, :dim_marital_status, {:dim_location=>[:dim_zip, :dim_business]}]
expected = [{:dim_location => [:dim_business, {:dim_city=>:dim_state}, :dim_zip]}, :dim_marital_status]
source2 = [{:dim_location=>{:dim_city=>:dim_state}}, {:dim_location=>:dim_city}]
def merge_dim_locations(array)
return array unless array.is_a?(Array)
values = array.dup
dim_locations = values.select {|x| x.is_a?(Hash) && x.has_key?(:dim_location)}
old_index = values.index(dim_locations[0]) unless dim_locations.empty?
merged = dim_locations.inject({}) do |memo, obj|
values.delete(obj)
x = merge_dim_locations(obj[:dim_location])
if x.is_a?(Array)
memo[:dim_location] = (memo[:dim_location] || []) + x
else
memo[:dim_location] ||= []
memo[:dim_location] << x
end
memo
end
unless merged.empty?
values.insert(old_index, merged)
end
values
end
puts "source1:"
puts source.inspect
puts "result1:"
puts merge_dim_locations(source).inspect
puts "expected1:"
puts expected.inspect
puts "\nsource2:"
puts source2.inspect
puts "result2:"
puts merge_dim_locations(source2).inspect
I don't think there's enough detail in your question to give you a complete answer, but this might get you started:
class Hash
def recursive_merge!(other)
other.keys.each do |k|
if self[k].is_a?(Array) && other[k].is_a?(Array)
self[k] += other[k]
elsif self[k].is_a?(Hash) && other[k].is_a?(Hash)
self[k].recursive_merge!(other[k])
else
self[k] = other[k]
end
end
self
end
end

Resources