Array with each_by_index [duplicate] - ruby

This question already has answers here:
Start a loop from 1
(5 answers)
Closed 9 years ago.
I'm using a loop that will access the value of an array. I'm using with_index to correctly display the results, however, arrays start at 0, but my DB values start at 1. So, when the array is iterated, and it reaches, index #6 (position 7 in the array) it stops and, therefore, the value stored at the seventh field is not displayed. I could be wrong, but that's what I think is happening.
I read that it's possible to pass arguments to the each_with_index method, in case the starting value should be other than 0, but I can't find how to do it.
I'm relatively new to working with arrays, and relatively new to Ruby as a whole.
EDIT
<% #by_ticket.each_with_index do |ticketshead, id| %>
<% #tickets[id].id %>
<% end %>
The #by_ticket is a group_by statement at the controller. When i loop through it, it brings back all but the last record that meets the parameters. My question is how to start the loop at 1, instead of 0. I'll check the provided link by Hitham S. AlQadheeb.
EDIT to correct a typo in code's line 2. Thanks.

The simplest solution I think is just incrementing the index in the block like the following:
['a', 'b', 'c'].each_with_index { |item, index| puts "#{item} #{index + 1}" }

Related

Ruby blocks behave unexpectedly when using "do" [duplicate]

This question already has answers here:
do..end vs curly braces for blocks in Ruby
(14 answers)
Closed 5 years ago.
I was trying to solve a coding puzzle: Take strings, and count the ones that don't include repeated words.
This code works:
def validate(passphrase)
words = passphrase.split
words == words.uniq
end
passphrases = File.readlines("../input/passphrases.txt")
p passphrases.count {|phrase| validate(phrase)}
#=> 337
If I make one minor change with the count block, it counts all of the passphrases instead of just the ones that would return true when passed through the block:
p passphrases.count do |phrase|
validate(phrase)
end
#=>512
What's up with this?
It is due to argument precedence with the do block.
Your first example is equivalent to:
p(passphrases.count {|phrase| validate(phrase)})
The second one with the do block is equivalent to:
p(passphrases.count) do |phrase|
validate(phrase)
end
Where the do is being applied to the p function.
If you want the second case to match the first, wrap the whole block in parenthesis:
p(passphrases.count do |phrase|
validate(phrase)
end)

what is the difference between .capitalize and .capitalize!(or .map & .map!...etc.) and in ruby [duplicate]

This question already has answers here:
What is the purpose of "!" and "?" at the end of method names?
(5 answers)
Closed 6 years ago.
learning how to code with Ruby and was trying learn from test first.
and I stumbled something funny.
I was trying to capitalize every word but
title = 'stuart little'
a = title.split
a.each do |x|
x.capitalize
end
a.join(' ')
This one's result is 'stuart little'
but if I add the ! in capitalize
title = 'stuart little'
a = title.split
a.each do |x|
x.capitalize!
end
a.join(' ')
it ends up with the result I want which is 'Stuart Little'
just .capitalize should work shouldn't it? since I'm just capitalizing the words. and what makes .capitalize! work in this scenario?
When a method has a ! at the end in Ruby, it is commonly referred to as a bang-method. The exclamation point indicates that the method is the dangerous version of another method.
In this case, capitalize! will modify your string, while capitalize will return a new string object. Since you are later calling on your original objects (the strings in a), your code will only work with capitalize!. To make the code work with capitalize, you would have to set that index of the array to the result of the method, e.g. a[index] = x.capitalize
if you really want to learn I like to go to the source
for map for map!. the source would tell you what the difference is
map- Invokes the given block once for each element of self.
and
map! - Invokes the given block once for each element of self,
replacing the element with the value returned by the block.

How do i print a string with repeated names followed by a number - Ruby? [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 6 years ago.
Improve this question
How do i print a name Ex. John1 and then print after John2, john3, john4, john5 and so one in an infinite number
I started using ruby today and I'm having some trouble figuring this out. I've searched some but can't find anything so how would I do this?
It's to mass produce accounts to the staff of a certain company and I found ruby to be the smartest to write it in and I will never use it again after this
Keep it simple.
puts (1..5).map { |n| "john#{n}" }
john1
john2
john3
john4
john5
The class Range includes the module Enumerable (as does the classes Array, Hash and others). By doing so, instances of Range (such as 1..5) gain the use of all of Enumerable's instance methods. One of Enumerable's instance methods is used here: Enumerable#map.
For printing a simple series like this:
n = 1
loop do
print 'john%d, ' % n
n += 1
end
That will never terminate, which makes it kind of silly. Maybe what you want is a bounded range:
list = (1..10).map do |n|
'john%d' % n
end.join(', ')
puts list
You can adjust the start and end values as necessary.
Perhaps use an enumerator here:
enum = Enumerator.new do |y|
i = 1
loop do
y << "John#{i}"
i += 1
end
end
enum.next #=> "John1"
enum.next #=> "John2"
enum.next #=> "John3"
Then use any one of the methods available to instances of Enumerator. Here we've used Enumerator#next to get the next "John" string.
One simple way is using a for loop. First declare an empty string variable that will hold our contents.
One important thing to consider is the index of the loop. If it's the last item, we do not want to add a separator like ", "
This is where the conditional comes into play. If the index is less than the last, we will add a comma and space, otherwise just the name.
Interpolation is done by wrapping a variable inside #{ and }
str = ""
for i in 1..5
str += i < 5 ? "john#{i}, " : "john#{i}"
end
Returns
"john1, john2, john3, john4, john5"

The difference between :+ and &:+ [duplicate]

This question already has answers here:
What are :+ and &:+ in Ruby?
(2 answers)
Closed 8 years ago.
I have code like this
list << num if num.to_s.split("").map(&:to_i).map(&:factorial).inject(:+) == num
It works, and I was wondering how inject works without the & (ampersand) in front of the :+. I am asking for someone to explain what the differences are between :+ and &:+.
&:+ is translated to a proc, while :+ is a Symbol. inject supports receiving symbols, which is translated internally to a proc:
If you specify a block, then for each element in enum the block is
passed an accumulator value (memo) and the element. If you specify a
symbol instead, then each element in the collection will be passed to
the named method of memo. In either case, the result becomes the new
value for memo. At the end of the iteration, the final value of memo
is the return value for the method.

How can I convert a step-down range to array? [duplicate]

This question already has answers here:
Is there a reason that we cannot iterate on "reverse Range" in ruby?
(12 answers)
Closed 10 years ago.
I have a range like (1000..0) and I was using each but it does not do anything. I was trying to convert it to an array and got an empty array.
I also tried (1000..0).step(-1).each and it tells me step cant be negative...
Is there any way to use (1000..0).each so it will do the repetition, or convert to an array like [1000,999,998,...,0]?
1000.downto(0).each { |i| ... }
Two ways you might go about doing this:
(0..1000).each do |i|
n = 1000 - i
# Use n for all calculations
end
(0..1000).to_a.reverse.each do |n|
# Involves creating temporary array, but overhead is usually minor for
# relatively small numbers.
end
Don't forget you can also do this without a range:
1001.times do |i|
n = 1000 - i
end
#1000 item array
step_down_array = 1000.step(0, -1).to_a
#small enumerator:
step_down = 1000.step(0, -1)
(0..1000).to_a.reverse
This will create the required array.

Resources