SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Guru Nick Carlson's Avatar
    Join Date
    Aug 2003
    Location
    Denver
    Posts
    644
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    A syntax question.

    Hello,

    Right now I'm reading Agile Web Development with Rails. I'm very new to ruby, and come from a mainly php background.

    I'm having trouble with the following ruby syntax:

    Code:
     def add_product(product)
       item = @items.find {|i| i.product_id == product.id}
       if item
     	item.quantity += 1
       else
     	item = LineItem.for_product(product)
     	@items << item
       end
       @total_price += product.price
     end
    Now, you don't have to know exactly what this function is doing. Basically, it's adding an item to a shopping cart. I'm having trouble understanding the syntax in the bolded line though.

    Would anyone be so kind as to rewrite that bolded line in PHP?

    Is "item" in that line an array? Or is it supposed to be true, false or nil? Where is |i| coming from? I know that || is a pipe, but I don't really understand the concept.

    One more question: With "if item", is that the same as "if (!empty($item))" in php?

    Thanks.
    ncarlson.net - a programmer's dystopia

  2. #2
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The {} thing is called block and is a fundamental concept in ruby.
    http://phrogz.net/ProgrammingRuby/tut_containers.html

    In php it may look like this:
    PHP Code:
    $item NULL;
    foreach(
    $items as $i) {
       if(
    $i->product_id == $product.id) {
          
    $item $i;
          break;
       }

    "if item" in ruby means item is not nil (NULL in php). Other values, even 0 or empty string, evaluate to true. Try this code:

    Code:
    #those are considered FALSE in php
    php_false = [0, "", "0", false, nil];
    php_false.each {|s| puts "in ruby #{s.inspect} is #{!!s}"}
    I'd suggest you read the pickaxe book before stating with rails.
    http://www.pragmaticprogrammer.com/t...uby/index.html

  3. #3
    SitePoint Guru Nick Carlson's Avatar
    Join Date
    Aug 2003
    Location
    Denver
    Posts
    644
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for taking the time to write that out stereofrog. That cleared in up for me. And that's a great link too.
    ncarlson.net - a programmer's dystopia


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •