Learning Ruby 3, Containers, Blocks, and Iterators

with<Programming Ruby>
Chapter 4
Containers, Blocks, and Iterators

Containers

Arrays
a = [ 3.14159,  "pie", 99 ]
a.class         Array
           →
a.length        3
           →
a[0]            3.14159
           →

b = Array.new
b.length   →0
b[0] = "second"
b[1] = "array"
b          → ["second", "array"]

   Positive → 0                                         Negative
                      1     2     3     4    5      6
    indices                                        −1 ← indices
              −7     −6    −5    −4    −3   −2
          a = “ant” “bat” “cat” “dog” “elk” “?y” “gnu”
      a[2] →              “cat”
     a[-3] →                          “elk”
  a[1..3] →         “bat” “cat” “dog”
a[-3..-1] →                           “elk” “?y” “gnu”
 a[4..-2] →                           “elk” “?y”

the index to [ ]= is two numbers (a start and a length) or a range
a = [ 1, 3, 5, 7, 9 ]   [1, 3, 5, 7, 9]
                      →
a[2, 2] = ’cat’         [1, 3, "cat", 9]
                      →
                        [1, 3, "dog", "cat", 9]
a[2, 0] = ’dog’       →
                        [1, 9, 8, 7, "dog", "cat", 9]
a[1, 1] = [ 9, 8, 7 ] →
a[0..3] = []            ["dog", "cat", 9]
                      →
a[5..6] = 99, 98        ["dog", "cat", 9, nil, nil, 99, 98]
                      →

Hashes (associative arrays, maps, or dictionaries)
h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }
h.length   →3
h['dog']   → "canine"
h['cow'] = 'bovine'
h[12]    = 'dodecine'
h['cat'] = 99
h          → {"cow"=>"bovine", "cat"=>99, 12=>"dodecine",
               "donkey"=>"asinine", "dog"=>"canine"}

Implementing a SongList Container

class SongList
  def append(song)
    @songs.push(song)
    self
  end
end

class SongList
  def delete_first
    @songs.shift
  end
  def delete_last
    @songs.pop
  end
end

class SongList
  def [](index)
    @songs[index]
  end
end

Blocks and Iterators

class SongList
  def with_title(title)
    @songs.find {|song| title == song.name }
  end
end
find is an iterator
iterator: a method that invokes a block of code repeatedly
    def three_times
      yield
      yield
      yield
    end
    three_times { puts "Hello" }
produces:
    Hello
    Hello
    Hello

i1, i2 = 1, 1 # parallel assignment (i1 = 1 and i2 = 1)

def fib_up_to(max)
  i1, i2 = 1, 1        # parallel assignment (i1 = 1 and i2 = 1)
  while i1 <= max
    yield i1
    i1, i2 = i2, i1+i2
  end
end
fib_up_to(1000) {|f| print f, " " }

if they appear for the ?rst time in the block, they’re local to the block. If instead they ?rst appeared outside the block, the variables will be shared between the block and the surrounding environment.
a = [1, 2]
b = 'cat'
a.each {|b| c = b * a[1] }
a                 [1, 2]
              →
b                 2
              →
defined?(c)       nil
              →

class Array
  def find
    for i in 0…size
      value = self[i]
      return value if yield(value)
    end
    return nil
  end
end
[1, 3, 5, 7, 9].find {|v| v*v > 30 }   7
                                     →
[ 1, 3, 5, 7, 9 ].each {|i| puts i }
["H", "A", "L"].collect {|x| x.succ } ["I", "B", "M"]

[1,3,5,7].inject(0) {|sum, element| sum+element}           16
                                                         →
[1,3,5,7].inject(1) {|product, element| product*element}   105
                                                         →

if inject is called with no parameter,it uses the ?rst element of the collection as the initial value and starts the iteration with the second value.
[1,3,5,7].inject {|sum, element| sum+element}           16
                                                      →
[1,3,5,7].inject {|product, element| product*element}   105
                                                      →

Blocks for Transactions
class File
  def File.open_and_process(*args)
    f = File.open(*args)
    yield f
    f.close()
  end
end

 *args, meaning “collect the actual parameters passed to the method into an array named args

Blocks Can Be Closures

songlist = SongList.new
class JukeboxButton < Button
  def initialize(label, &action)
    super(label)
    @action = action
  end
  def button_pressed
    @action.call(self)
  end
end
start_button = JukeboxButton.new("Start") { songlist.start }
pause_button = JukeboxButton.new("Pause") { songlist.pause }
                                                                         &action,Ruby looks for a code block whenever that method is called. That code block is converted to an object of class Proc and assigned to the parameter. You can then treat the parameter as any other variable. In our example, we assigned it to the instance variable @action. When the callback method button_pressed is invoked, we use the Proc#call method on that object to invoke the block.

method lambda, which converts a block to a Proc object.

def n_times(thing)
  return lambda {|n| thing * n }
end
p1 = n_times(23)
p1.call(3)   → 69
p1.call(4)   → 92
p2 = n_times("Hello ")
p2.call(3)   → "Hello Hello Hello "

發表在 Ruby on Rails | 留下評論

Rocky Balboa,2006

Rocky Balboa,2006
http://www.imdb.com/title/tt0479143/

我以為這是部動作片(顯然我對Sylvester Stallone的年紀問題看得太輕了),而影片的前面一大半卻比較沉悶,所以看得不很爽。
轉折發生在Rocky在街頭教訓自己的兒子那段, 聽着那段擲地有聲的精彩言論,我竟然突然感動要流淚!
挫敗後不要找別人出氣,而是要自己回擊!
看來Stallone不但勇猛,而且很有戰略,隨着自己年齡的增加,他巧妙地把影片的重心由動作轉到內涵上。
影片也再次讓我感受到美國老人的孤寂。

6

Rocky Balboa,2006
美國Las Vegas夜景, 聽說重慶也以夜景出名,不過還不能比較。

發表在 電影評論 | 留下評論

Learning Ajax 3, form and form observer

with <ajax on rails>

make fake form with the combination of link_to_remote and :submit option

3.4 Ajax Forms

form_for
remote_form_for

3.5

<%= form_tag :action => 'reverse' %>
  <p>Text to reverse: <%= text_field_tag 'text_to_reverse' %></p>
  <p id="reversed2"></p>
  <p><%= submit_to_remote 'submit', 'Reverse!',
          :update => 'reversed2',
          :url => { :action => 'reverse' } %></p>
<%= end_form_tag %>
the form can be submitted both via Ajax or non-Ajax methods. Consider this variation with two submit buttons
a common application for submit_to_remote would be checking a form for validity before actually submitting it for creation.

Form Observers

If :with doesn't contain an equal sign character (=), it's interpreted as a name for the parameterso foo becomes 'foo='+value. But if :with does contain an equal sign, it remains untouchedso foo=bar remains foo=bar.

:function => "alert(value)"

Observing an Entire Form
<form id="myForm">
  <p>Text to reverse: <%= text_field_tag 'text_to_reverse' %></p>
  <p id="reversed"></p>
</form>

<%= observe_form 'myForm',
      :update => "reversed",
      :url    => { :action => 'reverse' } %>
an observer for the form with the ID myForm, so that whenever any of its fields change, an Ajax.Updater call is created accordingly, which passes the serialized form values to the server.

發表在 Ruby on Rails | 留下評論

Learning Ajax 2, url, link and button

with <Ajax on Rails>
S2.3. Bringing Rails into the Picture

complex url_for example:
url_for :only_path => false, :protocol => ‘gopher:// ‘,
  :host => ‘example.com’, :controller =&gt; ‘chapter2′,
  :action => ‘myresponse’, :trailing_slash => true, :foo => ‘bar’,
  :anchor => ‘baz’
#=> ‘gopher://example.com/chapter2/myresponse?foo=bar/#baz’

ajax on rails(aor) alert:
<p><%= link_to_remote "Alert with javascript Helper", :url =>
   "/chapter2/myresponse", :success => "alert(request.responseText)" %></p>

aor insert:
<p><%= link_to_remote "Update  with javascript Helper", :url =>
  {:action => "myresponse"}, :update => "response5" %></p>
<p id="response5"></p>

Chapter 3. Introducing Prototype

3.2 Ajax Links

:method => :delete
<%= link_to "Delete", "/people/1", :method => :delete %>

==>
<a href="/people/1"
  onclick="var f = document.createElement(‘form’);
           f.style.display = ‘none’;
           this.parentNode.appendChild(f);
           f.method = ‘POST’;
           f.action = this.href;
           var m = document.createElement(‘input’);
           m.setAttribute(‘type’, ‘hidden’);
           m.setAttribute(‘name’, ‘_method’);
           m.setAttribute(‘value‘, ‘delete’);
           f.appendChild(m);
           f.submit(  );
           return false;">Delete</a>

Return false;
<a href="#"
   onclick="new Ajax.Updater(‘current_time’, ‘/chapter3/get_time’,
               {asynchronous:true, evalScripts:true});
            return false;">Check Time</a>
<div id="current_time"></div>
The link will only be followed if the expression evaluates true (or if the user has javascript turned off). That’s why the link_to_remote helper puts return false at the end of the onclick attribute.

Callbacks:
<%= link_to_remote "Check Time",
    :update   => ‘current_time’,
    :url      => { :action => ‘get_time’ },
    :before   => "$(‘indicator’).show(  )",
    :success  => "$(‘current_time’).visualEffect(‘highlight’)",
    :failure  => "alert(‘There was an error. ‘)",
    :complete => "$(‘indicator’).hide(  )" %>
<span id="indicator" style="display: none;">Loading…</span>
<div id="current_time"></div>

hide( ) and show( )
for an element to be dynamically shown via javascript, its CSS display: none property must be defined inline

this won’t work:
<style type="text/css">
  #indicator { display: none; }
</style>
<div id="indicator">Hidden DIV</div>
<script type="text/javascript">
  $("indicator").show(  ); // won’t work
</script>

But this will work:

<div id="indicator" style="display: none">Hidden DIV</div>
<script type="text/javascript">
  $("indicator").show(  ); // will work
</script>

:condition
<li><%= check_box_tag ‘checkbox’ %> Thing #1</li>
<%= link_to_remote "Delete checked items",
    :condition => "$(‘checkbox’).checked",
    :url       => { :action => ‘delete_items’ } %>

:submit
it allows you to simulate a form submission. By providing the ID of a page element, any fields contained in it will be sent along with the request.
<div id="fakeForm">
  <input type="text" name="foo" value="bar" />
</div>
<%= link_to_remote "Submit fake form",
       :submit   => "fakeForm",
       :url      => { :action => ‘repeat’ },
       :complete => "alert(request.responseText)" %>

nested forms

<form id="myForm">
  <input type="text" name="text_to_reverse" id="text_to_reverse" />
  <%= link_to_remote "Reverse field",
       :url      => { :action => ‘reverse’ },
       :submit   => "myForm",
       :complete => "$(‘text_to_reverse’).value=request.responseText" %>
  <input type="submit" />
</form>

:with
<%= link_to_remote "Link with params",
       :url      => { :action => ‘repeat’ },
       :complete => "alert(request.responseText)",
       :with     => "’foo=bar’" %>
two sets of quote marks. javascript expression

include references to javascript variables or DOM elements:
<input id="myElement" type="text" value="bar" />
<%= link_to_remote "Link with dynamic params",
       :url      => { :action => ‘repeat’ },
       :complete => "alert(request.responseText)",
       :with     => "’foo=’+escape($F(‘myElement’))" %>
escape it (so that it can safely be included in a URL query string)

link_to_function
<%= link_to_function "Toggle DIV", "$(‘indicator’).toggle(  )" %></p>
toggle( ), which hides and shows elements on the page.

button_to_function
<%= button_to_function "Greet", "alert(‘Hello world!’)" %>

combine with remote_function
<%= button_to_function "Check Time",
      remote_function(:update => "current_time",
        :url => { :action => ‘get_time’ }) %>

DIY button_to_remote
def button_to_remote(name, options = {})
  button_to_function(name, remote_function(options))
end
==>
<%= button_to_remote "Get Time Now",
      :update => "current_time",
      :url    => { :action => ‘get_time’ } %>

發表在 Ruby on Rails, 站長文檔 | 留下評論

Ruby on Rails, Layout

<%= render :partial => "person" %>

the partial is named "person," the main template will look for an instance variable @person, and pass it to the partial as a local variable, person.if the instance variable doesn't match the name of the partial, you'd explicitly pass it, like this:

<%= render :partial => "person", :locals => { :person => @scott } %>
All the key/value pairs in the :locals hash will be made into local variables for the partial.

<%= render :partial => "person", :collection => @people %>
In this example, the main template has an array @people that will be looped through, passing a local variable person to the partial.

render :layout => false
def reverse
  @reversed_text = params[:text_to_reverse].reverse
  render :layout => false
end

發表在 Ruby on Rails | 留下評論

Learning Ajax 1, Prototype

with <Ajax on Rails>
Chapter 2 .Getting Our Feet Wet

S2.1. The Old-Fashioned Way
<p><a href="#" onclick="asyncAlert(  )">Call async server-side</a></p>
<script type="text/javascript">
  function asyncAlert(  ) {
    //Call server(IE-safe)
    function getRequestObject(  ) {
      try { return new XMLHttpRequest(  ) } catch (e) {}
      try { return new ActiveXObject("Msxml2.XMLHTTP") } catch (e) {}
      try { return new ActiveXObject("Microsoft.XMLHTTP") } catch (e) {}
      return false
    }
    var request = getRequestObject(  );
    request.open('get', '/chapter2/myresponse');
    //we define a function that checks to see if readyState is 4 (which means the request is complete)
    request.onreadystatechange = function(  ) {
      if(request.readyState==4) alert(request.responseText);
    }
    request.send(  );
  }
</script>

s2.2. javascript Libraries and Prototype
Prototype Way:
<script src="/javascripts/prototype.js" type="text/javascript">
</script>
<p><a href="#" onclick="prototypeAlert(  );">Call with Prototype</a></p>
<script type="text/javascript">
 function prototypeAlert(  ) {
  new Ajax.Request('/chapter2/myresponse', { onSuccess: function(request) {
   alert(request.responseText);
  }})
 }
</script>

Update a element's innerHTML
<p><a href="#" onclick="updateElement(  )">Update element </a></p>
<p id="response"></p>
<script type="text/javascript">
  function updateElement(  ) {
    new Ajax.Request('/chapter2/myresponse', { onSuccess: function(request) {
      $('response').update(request.responseText);
    }})
  }
</script>

================>
<p><a href="#" onclick="updater(  )">Update with Ajax.Updater</a></p>
<p id="response2"></p>
<script type="text/javascript">
  function updater(  ) {
    new Ajax.Updater('response2', '/chapter2/myresponse');
  }
</script>

insert content:
<p><a href="#" onclick="appendToElement(  )">Append to element</a></p>
<p id="response3"></p>
<script type="text/javascript">
  function appendToElement(  ) {
    new Ajax.Updater('response3', '/chapter2/myresponse',
      { insertion:Insertion.Bottom });
  }
</script>
//insertions: Before, Top, Bottom, and After.

===============>
<p><a href="#" onclick="new Ajax.Updater('response4',
'/chapter2/myresponse', { insertion:Insertion.Bottom });">
Append to element</a></p>
<p id="response4"></p>

發表在 Ruby on Rails | 留下評論

A Bloody Aria, 2006

A Bloody Aria, 2006
http://www.imdb.com/title/tt0821462/

好噁心, 沒想到韓石圭會參演這樣的電影。
不過剛開始那一小段很不錯。
4

發表在 電影評論 | 留下評論

大電影之數百億, 2006

大電影之數百億, 2006

搞的電影沒有想像中多,也沒有想像中惡。。。

5

發表在 電影評論 | 留下評論

Google的病毒式營銷

Google AdSense廣告收入是Google收入的主要來源之一。
Google AdSense讓站長發布其廣告,與站長瓜分收益,同時又讓以重金為酬,讓站長向其它站長或公司推薦AdSense和與其相對的廣告收集項目AdWords. 站長們一傳十,十傳百, 不用專門的推銷人員,省下管理了人員,卻帶來乘方式的回報。這種新式的病毒式營銷既與Google這類早去蓬勃的信息產業類型門當戶對, 又低耗高效, 實在是高!

Google在其它領域使用的病毒式營銷
Gmail的邀請式註冊

病毒式營銷(viral marketing/viral advertising)

self-replicating viral processes
analogous to the spread of pathological
to obtain a large number of interested people at a low cost.

Word of Mouth Marketing (WOMM)

發表在 信息處理 | 留下評論

Babel,2006

Babel,2006

http://www.imdb.com/title/tt0449467/
今天去書店看到一本名為

的書,可能很是暢銷,被擺在了電梯口。
看來很多人都發現這個世界越來越小了。
我也很想說明萬物是關聯的,用電影,告訴大家,今天在街上和你擦肩而過的,今天之前你不認識,今天之後你們或許也永遠沒有機會再次相見的人,卻可能是和你關聯着的。

感覺這片的結構是這個意思,但內容卻比較分散。兩年前(?)類似的電影<Crash>給我的印象好一些。

7

Babel,2006
繁華的日本都市

Babel,2006
這是一套很爽的房子,下面跟着電影鏡頭重點參觀一下,看點是它的陽台

Babel,2006
透過窗戶可以看到都市夜景

Babel,2006
繞過那個窗戶可以出到陽台

Babel,2006
陽台上看到的美麗夜景

Babel,2006
偶爾陽台本身也可以成為風景

Babel,2006
大廈遠景(左部那橦),那套房子是頂層(31樓或以上樓層)右角

發表在 電影評論 | 一條評論