|
| 1 | +# Next |
| 2 | + |
| 3 | +In Ruby, the `next` keyword is used to skip the rest of the current iteration and move to the next iteration of a loop or block. It's similar to `continue` in other programming languages. |
| 4 | + |
| 5 | +```ruby |
| 6 | +# Basic next usage in a loop |
| 7 | +["README.md", ".git", "lib", ".gitignore"].each do |path| |
| 8 | + next if path.start_with?(".") |
| 9 | + puts "Processing: #{path}" |
| 10 | +end |
| 11 | +# Output: |
| 12 | +# Processing: README.md |
| 13 | +# Processing: lib |
| 14 | +``` |
| 15 | + |
| 16 | +The `next` statement can be used with any of Ruby's iteration methods or blocks. |
| 17 | + |
| 18 | +```ruby |
| 19 | +# Using next with different iterators |
| 20 | +users = [ |
| 21 | + { name: "Alice", active: true }, |
| 22 | + { name: "Bob", active: false }, |
| 23 | + { name: "Carol", active: true } |
| 24 | +] |
| 25 | + |
| 26 | +# With each |
| 27 | +users.each do |user| |
| 28 | + next unless user[:active] |
| 29 | + puts "Notifying #{user[:name]}" |
| 30 | +end |
| 31 | +# Output: |
| 32 | +# Notifying Alice |
| 33 | +# Notifying Carol |
| 34 | + |
| 35 | +# With map |
| 36 | +messages = users.map do |user| |
| 37 | + next "Account inactive" unless user[:active] |
| 38 | + "Welcome back, #{user[:name]}!" |
| 39 | +end |
| 40 | +puts messages.inspect |
| 41 | +# Output: |
| 42 | +# ["Welcome back, Alice!", "Account inactive", "Welcome back, Carol!"] |
| 43 | +``` |
| 44 | + |
| 45 | +## Conditional Next |
| 46 | + |
| 47 | +The `next` keyword is often used with conditions to create more complex iteration logic. |
| 48 | + |
| 49 | +```ruby |
| 50 | +# Processing specific elements |
| 51 | +orders = [ |
| 52 | + { id: 1, status: "paid" }, |
| 53 | + { id: 2, status: "pending" }, |
| 54 | + { id: 3, status: "cancelled" }, |
| 55 | + { id: 4, status: "paid" } |
| 56 | +] |
| 57 | + |
| 58 | +orders.each do |order| |
| 59 | + # Skip non-paid orders |
| 60 | + next unless order[:status] == "paid" |
| 61 | + puts "Processing payment for order #{order[:id]}" |
| 62 | +end |
| 63 | +# Output: |
| 64 | +# Processing payment for order 1 |
| 65 | +# Processing payment for order 4 |
| 66 | + |
| 67 | +# Processing with multiple conditions |
| 68 | +products = [ |
| 69 | + { name: "Book", price: 15, in_stock: true }, |
| 70 | + { name: "Shirt", price: 25, in_stock: false }, |
| 71 | + { name: "Hat", price: 12, in_stock: true } |
| 72 | +] |
| 73 | + |
| 74 | +products.each do |product| |
| 75 | + next unless product[:in_stock] # Skip out of stock items |
| 76 | + next if product[:price] > 20 # Skip expensive items |
| 77 | + puts "Featured item: #{product[:name]} at $#{product[:price]}" |
| 78 | +end |
| 79 | +# Output: |
| 80 | +# Featured item: Book at $15 |
| 81 | +# Featured item: Hat at $12 |
| 82 | +``` |
| 83 | + |
| 84 | +The `next` keyword helps control the flow of iterations, allowing you to skip unwanted elements or conditions while continuing the loop. |
0 commit comments