Say I have an array like this:
["auburn", "http://auburn.craigslist.org/web/", "http://auburn.craigslist.org/cpg/", "http://auburn.craigslist.org/eng/", "http://auburn.craigslist.org/sof/", "http://auburn.craigslist.org/sad/"]
What I would like to do is work on just the URLs in this array - which will always start at element[1]
and go up.
How do I do that?
We can also create an array in Ruby by assigning the value to the array of each element.In the below example we have simply used the new class with passing two argument to it , one is the length of the array and and another the element which is going to repeatedly used as the element of the array.
In Ruby the C-like for-loop is not in use. Instead of that people usually iterate over the elements of an array using the each method. examples/ruby/iterating_on_array.rb. names = ['Foo', 'Bar', 'Baz'] puts names puts names.each { |item| puts item } puts names.each do |item| puts item end. In this example we have an array with 3 elements.
def cycle (my_list, start_at=None): start_at = 0 if start_at is None else my_list.index (start_at) while True: yield my_list [start_at] start_at = (start_at + 1) % len (my_list) This will return an (infinite) iterator looping your list. To get the next element in the cycle you must use the next statement:
Adding the Element to the end of the Array : Here in this way we are adding the array element at the end of the existing array . First we added with operator << at the end and then we used the method push to add the new attribute at the end of the array .Please see the below example along with screen of output.
This only shows the elements starting from 1 (the second element), -1 stands for the last element
a = ["auburn", "http://auburn.craigslist.org/web/", "http://auburn.craigslist.org/cpg/", "http://auburn.craigslist.org/eng/", "http://auburn.craigslist.org/sof/", "http://auburn.craigslist.org/sad/"]
p a[1..-1]
=> ["http://auburn.craigslist.org/web/", "http://auburn.craigslist.org/cpg/", "http://auburn.craigslist.org/eng/", "http://auburn.craigslist.org/sof/", "http://auburn.craigslist.org/sad/"]
a = ["auburn", "http://auburn.craigslist.org/web/", "http://auburn.craigslist.org/cpg/", "http://auburn.craigslist.org/eng/", "http://auburn.craigslist.org/sof/", "http://auburn.craigslist.org/sad/"]
a.drop(1).each { |m| puts m }
#=> http://auburn.craigslist.org/web/
# http://auburn.craigslist.org/cpg/
# http://auburn.craigslist.org/eng/
# http://auburn.craigslist.org/sof/
# http://auburn.craigslist.org/sad/
a[1..-1] will return the array with the first item removed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With