escaping the .each { } iteration early in Ruby
While the break
solution works, I think a more functional approach really suits this problem. You want to take
the first 10 elements and print them so try
items.take(10).each { |i| puts i.to_s }
escaping the .each { } iteration early in Ruby
While the break
solution works, I think a more functional approach really suits this problem. You want to take
the first 10 elements and print them so try
items.take(10).each { |i| puts i.to_s }
The most idiomatic way to iterate through a Ruby array, exiting when an arbitrary condition met?
take
and drop
have a variant take_while
and drop_while
where instead of providing a fixed number of elements you provide a block. Ruby will accumulate values from the receiver (in the case of take_while) as long as the block returns true. Your code could be rewritten as
array.take_while {|pair| pair.sum < foo}.map(&:sum)
This does mean that you calculate the sum of some of these pairs twice.
Count iteration on the Enumerable cycle
You can put something like that together fairly easily. Something like
class Iter < Array
attr_reader :iteration
def initialize(*args)
super(*args)
@pointer = 0
@iteration = 1 # Current iteration
end
def next
self[@pointer].tap {
@pointer = (@pointer + 1) % size
@iteration += 1 if @pointer == 0
}
end
end
iter = Iter.new [1,2,3]
7.times { puts 'iteration %d: %d' % [iter.iteration, iter.next] }
# iteration 1: 1
# iteration 1: 2
# iteration 1: 3
# iteration 2: 1
# iteration 2: 2
# iteration 2: 3
# iteration 3: 1
Ruby: de-escape special symbols in a loop
There unfortunately isn't a "good" way to do this. The normal case for needing this is decoding a transport format like AJAX, but those libraries just implement the correct mapping themselves, so you rarely need it in your own code. You have two options, really:
Write out the mapping yourself, as you did in your original code. One thing you could do to make it more readable would be to create a dictionary and loop over that rather than chaining gsubs.
Use
eval
to create a string. For example:c = 'n'
newline = eval "\"\\#{c}\""
Best way to escape and unescape strings in Ruby?
Ruby 2.5 added String#undump
as a complement to String#dump
:
$ irb
irb(main):001:0> dumped_newline = "\n".dump
=> "\"\\n\""
irb(main):002:0> undumped_newline = dumped_newline.undump
=> "\n"
With it:
def escape(s)
s.dump[1..-2]
end
def unescape(s)
"\"#{s}\"".undump
end
$irb
irb(main):001:0> escape("\n \" \\")
=> "\\n \\\" \\\\"
irb(main):002:0> unescape("\\n \\\" \\\\")
=> "\n \" \\"
Ruby efficient each loop
You could:
- use
puts
instead of<<
to avoid explicit newlines - use
center
to center the caption horizontally - use
map
to generate the attribute strings and utilizeputs
' behavior of printing array elements on separate lines - use
without
to get a hash without the:Module
key - use
*
to repeat a string
Applied to your code:
markdown = StringIO.new
coverage_hash_arr.each do |hash|
markdown.puts " Status on #{hash[:Module]} ".center(46, '-')
markdown.puts hash.without(:Module).map { |k, v| "- #{k}: #{v}" }
markdown.puts '-' * 46
markdown.puts
end
Output via puts markdown.string
:
-------------- Status on Mobile --------------
- name: Sheila Chapman
- age: 21
----------------------------------------------
--------------- Status on Web ----------------
- name: Hendricks Walton
- age: 40
----------------------------------------------
--------------- Status on Misc ---------------
- name: Torres Mcdonald
- age: 39
----------------------------------------------
Note that the above isn't proper Markdown syntax. You might want to change your output to something like this:
### Status on Mobile
- name: Sheila Chapman
- age: 21
### Status on Web
- name: Hendricks Walton
- age: 40
### Status on Misc
- name: Torres Mcdonald
- age: 39
Values are skipped during array nested iteration in Ruby
If i understood correctly, maybe you could take a slightly different approach:
Considering this
id[0]--> store[0]-->group[0]
id[1]--> store[1]-->group[1]
then you don't need to nest loops, you could try looping only once and use an index to fetch each value form each array, something like this:
(0..id.size - 1).each do |i|
puts "For ID: #{id[i]}"
value = File.open("#{file_dir}/#{file_name[i]}_details.txt")
text = File.read(value)
text.each_line do |line|
if line.match(/#{group[i]}/)
print "group row #{group[i]}\n"
print "Its matching\n"
replace = text.gsub(/#{Regexp.escape(id[i])}\,\s/, '')
.gsub(/#{Regexp.escape(id[i])}/, '')
.gsub(/,\s*$/, '')
else
print "Not\n"
print "group row #{group[i]}\n"
end
end
end
This code assumes that id
, file_name
and group
will always have the same size.
Related Topics
Which Ruby Rest API Client for Neo4J
Ruby JSON.Pretty_Generate ... Is Pretty Unpretty
How to Redirect Back to a Page I'M Currently On
Convert Named Matches in Matchdata to Hash
Ruby: How to Load .Rb File in The Local Context
Ruby String#Scan Equivalent to Return Matchdata
Alternative for Accepts_Nested_Attributes_For - Maybe Virtus
What's The Impact of Eager_Load=True
Ruby Group Hashes by Value of Key
Howto: Model Scope for Todays Records
Ruby Comparison Operators? == VS. ===
Mocking Chain of Methods in Rspec
Rails App Moved to Production Server Gives "Dump Format Error for Symbol" Error
Specify Custom Index Name When Using Add_Reference