I am trying to understand this standalone method for practice [closed] - ruby

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.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Improve this question
Im trying to write a standalone method named count_lines that returns the number of lines in an input string.
If i run this test code it should produce the output shown:
s = %W/This
is
a
test./
print "Number of lines: ", count_lines(s), "\n"
# Output:
Number of lines: 4
I am fairly new to Ruby and I am trying to figure out if this pseudocode of the actual output or not. Please help me!!

I would assume count_lines is a method that counts the number of elements in a an array, you can count the number of elements using of the several methods ruby provides look up the Array Documentation for this, and %W is a one of ruby niceties which allows you create an array of strings, e.g:
arr = %W{a b c}
arr # => ["a", "b", "c"]
It takes almost any special character as a delimiter e.g using . as a delimeter
arr = %W.a b c.
arr # => ["a", "b", "c"]
So in your snippet from the question / is delimiter used, so s would evaluate as below:
s = %W/This
is
a
test./
s # => ["This", "is", "a", "test."]
The above explains why the below works as it does
def count_lines(arr)
arr.size
end
s = %W/This
is
a
test./
print "Number of lines: ", count_lines(s), "\n"
# >> Number of lines: 4

Related

TypeError Parsing Ruby Array of Hashes [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 1 year ago.
Improve this question
I have an Array of Ruby Hashes that I'm trying to iterate so that I can parse values by key.
forms = {"forms":[{"id":123,"name":"John","created_at":"2021-11-23T21:41:17.000Z"},{"id":456,"name":"Joe","created_at":"2021-11-21T05:17:44.000Z"}]}
forms.each do |form|
puts form ## {:id=>123, :name=>"John", :created_at=>"2021-11-23T21:41:17.000Z"}
puts form["id"]
end
This yields the following error:
main.rb:4:in `[]': no implicit conversion of String into Integer (TypeError)
I'm admittedly a big Ruby noob, but can't figure this out. I've also tried puts form[:id] and puts form[":id"] to no avail.
Note: I don't have any control over the Array of Hashes that's being assigned to the forms variable. It's what I get back from an external API call.
Your forms is a Hash. If you do each on Hash it passes to the block each key & value pair.
forms.each do |key, value|
p key # => :forms
p value # => [{....}]
p value.map { |v| v[:id] }
end
There's also this, in case the forms always has the forms key (doesn't change)
forms[:forms].map { |v| v[:id] }

ruby not equal operator doesn't work but equal does [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm very puzzled with this simple method I have where I'm just trying to puts a character of an array if, when compared with the character of another array, it is different.
This works with the == operator but not with the !=
Maybe it has to do with the each loops but I can't see what the error is. Any ideas?
Thanks
def remove_vowels(s)
nw_s = s.chars
vowels = "aeiou".chars
result = []
nw_s.each do |char|
vowels.each do |vowel|
if char != vowel
print char
end
end
end
end
remove_vowels("apple")
Nested each is no ruby way of doing this kind of task. You can write this
def remove_vowels(s)
nw_s = s.chars
vowels = "aeiou".chars
result = nw_s.map {|k| k unless vowels.include?(k) }.compact
end
remove_vowels("apple")
One line of code instead seven

What's The Ruby Community's Preferred Type of Loop? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Self teaching myself Python, I've taken a Computer Science class that taught in Java. I've noticed that for loops are the gold standard for each language. Yet prowling around this website and other tutortials, the for loop is no where to be found, despite it being in Ruby and, (in my opinion) it's pretty straight forward and well known syntax. Whats wrong with for loops?
Since Ruby offers a plethora of ways to accomplish a task, which type of loop is the most popular and why?
Ruby is unusual in that you really do not ever use for. There's always a better tool for the job. For example:
n.times do |i|
# for (i = 0; i < n; ++i) in other languages
end
10.upto(20) do |i|
# for (i = 10; i < 20; ++i) in other languages
end
a = [ 1, 2, 4, 8, 16 ]
a.each do |v|
# for (v in a) in other languages
end
a = [ 1, 2, 4, 8, 16 ]
a.map do |v|
# .map(v => ...) in JavaScript
end
The Enumerable module is the source of a lot of Ruby's power because it's available on things like Hash, Array, and others, as well as things that can be easily converted to those things, which is an even bigger list of options.
What's a complex problem to solve in other languages is often a few simple transformations in Ruby and nary a for loop.
An important property of Enumerable methods is that these often emit an Enumerator which can be used to chain operations together, like this:
10.upto(20).with_index.map do |i, j|
# Provides pairs like [ 10, 0 ], [ 11, 1 ], etc.
i + j
end
Where that provides both a value, an index, and a way of converting or combining those into a subsequent result which itself can be iterated, altered, or otherwise transformed.

How to remove duplicate values in an array without using unique method in 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 5 years ago.
Improve this question
I have a program where values in an array are [1,2,46,5,8,2,8], now I want to remove duplicate values but without using unique method of Ruby. Can anyone help with the logic of doing it? I want to make a unique array.
The code that I am using is may be not absolute to the question which is why I am getting the answer to first two situations but not the last one. Here is the code :
def uniq(array)
i=0
while i < array.length
if array[i] == array[i+1]
puts ""
else
puts i
end
i += 1
end
end
uniq([5,5,5,5])
uniq([1])
uniq([1,2,46,5,8,2,8])
Another way is to convert to a Set which will remove the duplicates, then convert back to an array. First require 'set' (in the Standard Lib) then, either of these:
Set.new([1,2,3,3]).to_a
# => [1, 2, 3]
# Does the same thing without passing the array to the Set constructor
[1,2,3,3].reduce(Set.new, &:add).to_a
# => [1, 2, 3]
You could use the intersection or union:
arr = [1,2,46,5,8,2,8]
# => [1,2,46,5,8,2,8]
unique_arr = arr & arr
# => [1, 2, 46, 5, 8]

Accessing the contents of an Array containing a hash in Ruby [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am new to ruby and trying out some examples.I have the array below that contains a hashmap.
f = [{"qty"=>"5", "unit"=>"kgs", "item"=>"sugar", "cost"=>"400", "salestax"=>"0.0"}]
I want to print out some thing like this
5 kgs of sugar : 400 at a tax of 0.0(if you notice the content is from the hashset)
I've tried some thing like:
f.each
{
|m| puts m for u in m |qty,unit,item,cost,salestax| puts "#{qty} #{unit} of #{item} : #{cost} #{salestax}"
}
but its not giving me what I want.
f.each do |hash|
puts "#{hash['qty']} #{hash['unit']} of #{hash['item']}: #{hash['cost']} at a tax of #{hash['salestax']}."
end
Seems like that is what you want.
Another way
f.each { |hash| puts "%s %s of %s : %s at a tax of %s" % hash.values }

Resources