Saturday, January 15, 2011

Writing Ruby Extensions in C - Part 9, Arrays

This is the ninth in my series of posts about writing ruby extensions in C. The first post talked about the basic structure of a project, including how to set up building. The second post talked about generating documentation. The third post talked about initializing the module and setting up classes. The fourth post talked about types and return values. The fifth post focused on creating and handling exceptions. The sixth post talked about ruby catch and throw blocks. The seventh post talked about dealing with numbers. The eighth post talked about strings. This post will focus on arrays.

Arrays


The nice thing about arrays in ruby C extensions is that they act very much like the ruby arrays they represent. There are a few functions to know about:
  • rb_ary_new() - create a new array with 0 elements. Elements can be added later using rb_ary_push(), rb_ary_store(), or rb_ary_unshift().
  • rb_ary_new2(size) - create a new array with size elements
  • rb_ary_store(array, index, value) - put the ruby value into array at index. This can be used to create sparse arrays; intervening elements that have not yet had values assigned will be set to nil
  • rb_ary_push(array, value) - put value at the end of the array
  • rb_ary_unshift(array, value) - put value at the start of the array
  • rb_ary_pop(array) - pop the last element of array off and return it
  • rb_ary_shift(array) - remove the first element of array and return it
  • rb_ary_entry(array, index) - examine array element located at index without changing array
  • rb_ary_dup(array) - copy array and return the copy
  • rb_ary_to_s(array) - invoke the "to_s" method on the array. Note that this concatenates the array elements together without spacing, so is not generally useful
  • rb_ary_join(array, string_object) - create a string by converting each element of the array to a string separated by string_object. If string_object is Qnil, then no separator is used
  • rb_ary_reverse(array) - reverse the order of all of the elements in array
  • rb_ary_to_ary(ruby_object) - create an array out of any ruby object. If the object is already an array, a reference to the same object is returned. If the object supports the "to_ary" method, then "to_ary" is invoked on the object and the result is returned. If neither of the previous are true, then a new array with 1 element containing the object is returned

An example should make most of this clear:

 1) VALUE result, elem, arr2, mystr;
 2)
 3) result = rb_ary_new();
 4) // result is now []
 5) rb_ary_push(result, INT2FIX(1));
 6) // result is now [1]
 7) rb_ary_push(result, INT2FIX(2));
 8) // result is now [1, 2]
 9) rb_ary_unshift(result, INT2FIX(0));
10) // result is now [0, 1, 2]
11) rb_ary_store(result, 3, INT2FIX(3));
12) // result is now [0, 1, 2, 3]
13) rb_ary_store(result, 5, INT2FIX(5));
14) // result is now [0, 1, 2, 3, nil, 5]
15) elem = rb_ary_pop(result);
16) // result is now [0, 1, 2, 3, nil] and elem is 5
17) elem = rb_ary_shift(result);
18) // result is now [1, 2, 3, nil] and elem is 0
19) elem = rb_ary_entry(result, 0);
20) // result is now [1, 2, 3, nil] and elem is 1
21) arr2 = rb_ary_dup(result);
22) // result is now [1, 2, 3, nil] and arr2 is [1, 2, 3, nil]
23) mystr = rb_ary_to_s(result);
24) // result is now [1, 2, 3, nil] and mystr is 123
25) mystr = rb_ary_join(result, rb_str_new2("-"));
26) // result is now [1, 2, 3, nil] and mystr is 1-2-3-
27) rb_ary_reverse(result);
28) // result is now [nil, 3, 2, 1]
29) rb_ary_shift(result);
30) // result is now [3, 2, 1]
31) result = rb_ary_to_ary(rb_str_new2("hello"));
32) // result is now ["hello"]

37 comments:

  1. This blog awesome and i learn a lot about programming from here.The best thing about this blog is that you doing from beginning to experts level.

    Love from

    ReplyDelete
  2. toptan iç giyim tercih etmenizin sebebi kaliteyi ucuza satın alabilmektir. Ürünler yine orjinaldir ve size sorun yaşatmaz. Yine de bilinen tekstil markalarını tercih etmelisiniz.

    Digitürk başvuru güncel adresine hoşgeldiniz. Hemen başvuru yaparsanız anında kurulum yapmaktayız.

    tutku iç giyim Türkiye'nin önde gelen iç giyim markalarından birisi olmasının yanı sıra en çok satan markalardan birisidir. Ürünleri hem çok kalitelidir hem de pamuk kullanımı daha fazladır.

    nbb sütyen hem kaliteli hem de uygun fiyatlı sütyenler üretmektedir. Sütyene ek olarak sütyen takımı ve jartiyer gibi ürünleri de mevcuttur. Özellikle Avrupa ve Orta Doğu'da çokça tercih edilmektedir.

    yeni inci sütyen kaliteyi ucuz olarak sizlere ulaştırmaktadır. Çok çeşitli sütyen varyantları mevcuttur. iç giyime damga vuran markalardan biridir ve genellikle Avrupa'da ismi sıklıkla duyulur.

    iç giyim ürünlerine her zaman dikkat etmemiz gerekmektedir. Üretimde kullanılan malzemelerin kullanım oranları, kumaşın esnekliği, çekmezlik testi gibi birçok unsuru aynı anda değerlendirerek seçim yapmalıyız.

    iç giyim bayanların erkeklere göre daha dikkatli oldukları bir alandır. Erkeklere göre daha özenli ve daha seçici davranırlar. Biliyorlar ki iç giyimde kullandıkları şeyler kafalarındaki ve ruhlarındaki özellikleri dışa vururlar.

    ReplyDelete
  3. instagram takipçi satın al
    instagram takipçi satın al
    takipçi satın al
    instagram takipçi satın al
    instagram takipçi satın al
    takipçi satın al
    instagram takipçi satın al
    aşk kitapları
    tiktok takipçi satın al
    instagram beğeni satın al
    youtube abone satın al
    twitter takipçi satın al
    tiktok beğeni satın al
    tiktok izlenme satın al
    twitter takipçi satın al
    tiktok takipçi satın al
    youtube abone satın al
    tiktok beğeni satın al
    instagram beğeni satın al
    trend topic satın al
    trend topic satın al
    youtube abone satın al
    beğeni satın al
    tiktok izlenme satın al
    sms onay
    youtube izlenme satın al
    tiktok beğeni satın al
    sms onay
    sms onay
    perde modelleri
    instagram takipçi satın al
    takipçi satın al
    tiktok jeton hilesi
    pubg uc satın al

    ReplyDelete
  4. On your place I would make a video how to write ruby extensions in c part 9. I would post such video on youtube and get some likes on this site https://soclikes.com

    ReplyDelete
  5. Appreciate it for this post 무료야설 , I am a big big fan of this web site would like to proceed updated.

    ReplyDelete
  6. Good information here 오피헌터. I really enjoy reading them every day. I’ve learned a lot from them. Thanks so much for sharing this information.

    ReplyDelete
  7. After I originally left a comment I appear to have clicked on the -Notify me when new comments are added- checkbox and from now on every time a comment is added I receive 4 emails with the exact same comment. Perhaps there is an easy method you are able to remove me from that service? Thank you! 타이마사지

    ReplyDelete
  8. Thanks , I have just been looking for information approximately this subject for a while and yours is the greatest I've found out till now. However, what concerning the conclusion? Are you sure about the source? 안마

    ReplyDelete
  9. I guess your website appears adorable. The successful points are given in this text.That is in reality very extraordinary recommendations are given in this article.. The Satta King is the satta king result provider website, Which provide the satta king fast result in Ghaziabad Satta King, Faridabad Satta King, Delhi satta king, Desawar Gali result and many more.

    Best Satta King Result Site: Satta King

    ReplyDelete
  10. When I read your article on this topic, the first thought seems profound and difficult. There is also a bulletin board for discussion of articles and photos similar to this topic on my site, but I would like to visit once when I have time to discuss this topic. sòng bạc


    ReplyDelete
  11. This is a very interesting post. Thank you for posting a lot of interesting posts. And please visit my site!~! The name of the site is 슬롯사이트.

    ReplyDelete
  12. .Sometimes life hits hard
    It’s hard to cope with everything by myself, so having a friend like you is the greatest blessing I have ever received. I’m beyond thankful for your support and understanding, buddy
    .You are the best. دانلود آهنگ محسن ابراهیم زاده جانم تو

    ReplyDelete
  13. Good financial planners and advisors are compared to life coaches because they can help with many complex financial decisions throughout your life. They deal with other financial professionals daily and typically know if you’re paying too much for something or not getting a competitive rate.

    ReplyDelete
  14. Apakah Anda ingin memulai bisnis yang menguntungkan namun tidak tahu bagaimana cara menentukan ide bisnis yang kreatif dan inovatif? Jika iya, mari simak berikut ini 30 cara menentukan ide bisnis yang bisa Anda jadikan inspirasi.

    ReplyDelete
  15. Our vegan menu crafted by Indian food in Bali specialists and top-rated chefs, is the first of its kind on Seminyak We feel that everyone in Bali should have the opportunity to experience the difference Queens Indian Cuisine brings to the table, whether you are on Seminyak - Kuta - Nusa Dua - Ubud – the best Indian food in Bali is here. We are Bali's best-kept secret in the search for amazing Indian food.

    ReplyDelete
  16. An investment property is a property that has been purchased for the sole purpose of generating income. Investment properties in Bali Investment properties in Bali can produce a return on investment in the form of rental returns or capital growth. Capital growth occurs when the value of the property has increased over time.

    ReplyDelete
  17. That is the reason selling promoting efforts showcasing with the goal that you could significant investigate past advertisment. Simply to scribble down more grounded set that fit this depiction. 먹튀검증업체

    ReplyDelete
  18. I've been looking for photos and articles on this topic over the past few days due to a school assignment, casinocommunity and I'm really happy to find a post with the material I was looking for! I bookmark and will come often! Thanks :D

    ReplyDelete