Newbie question: Small blocks

ruby

    Next

  • 1. sort_by to accept symbol?
    hi I was wondering whether it'd be useful for Array#sort_by to accept a symbol as an alternative to a block for the sort rule. So my_array.sort_by(:foo) would mean my_array.sort_by { | elem | elem.send(:foo) } It's not so much to save typing as to make it neater to use sort_by in chained method calls. Any takers? alex

Re: Newbie question: Small blocks

Postby Joel VanderWerf » Wed, 12 Sep 2007 04:37:55 GMT



Maybe this?

class Symbol
   def to_proc
     proc {|x,*args| x.send(self, *args)}
   end
end

[1,2,3].map(&:to_s)    # ==> ["1", "2", "3"]

-- 
        vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407


Re: Newbie question: Small blocks

Postby Phlip » Wed, 12 Sep 2007 04:38:24 GMT




If I guess correctly, ActiveSupport has a cute little tweak that permits 
this:

p (0..10).to_a.map(&:to_s)

Any place you can write {|x| x.y}, you can shorten that to (&:y). This works 
great with ActiveRecord, to convert a list of database records into a list 
of one of its fields:

 p User.find(:all).map(&:name)

-- 
  Phlip 



Re: Newbie question: Small blocks

Postby Phlip » Wed, 12 Sep 2007 04:44:52 GMT




*args?! Nobody told me you could pass args in too!

-- 
 Phlip
  http://www.**--****.com/ 
 ^ assert_xpath
  http://www.**--****.com/ ;-- assert_latest Model


Re: Newbie question: Small blocks

Postby Jeremy Woertink » Wed, 12 Sep 2007 04:52:13 GMT

You can type any block with the  { } or the do..end way. You don't have 
to have the pipes, but without them you don't have a way to pass items 
of your collection into the block. So for example

array.each { puts "HELLO" } <--- no pipes, but no data

The only thing I can think of where you would have seen the & would be 
something like

irb(main):001:0> (0..5).each { 0 & 5 }
=> 0..5
irb(main):002:0>


~Jeremy
-- 
Posted via  http://www.**--****.com/ 


Re: Newbie question: Small blocks

Postby dblack » Wed, 12 Sep 2007 04:54:22 GMT

Hi --





You don't want the 'do' on the braces version though. (And yes, I've
done it occasionally :-)


David

-- 
* Books:
   RAILS ROUTING (new!  http://www.**--****.com/ )
   RUBY FOR RAILS ( http://www.**--****.com/ )
* Ruby/Rails training
     & consulting:  Ruby Power and Light, LLC ( http://www.**--****.com/ )


Re: Newbie question: Small blocks

Postby Jeremy Woertink » Wed, 12 Sep 2007 04:54:52 GMT





I totally forgot about that one. I guess I was thinking just Ruby and 
not anything with rails. :)


~Jeremy
-- 
Posted via  http://www.**--****.com/ 


Similar Threads:

1.newbie question about blocks


Hi, I want to square every element in my array using a block:

a = (1..1000).to_a
a.each {|x| x**2}

But this does not seem to work, it just outputs my array completely
unchanged :(

--
"winners never quit, quitters never win"

2.Newbie Question: Blocks and Parameters

3.Newbie question re. blocks & variable scope

Hi,

I'd like to ask for some help with local variable scope.  I understand
that the scope of a local variable is the "do...end" block in which it
is created.  However, the code below shows that the value assigned to
the variable within a block does not persist after the single
iteration in which the variable is given that value, although the
variable is still defined in a later iteration. That is, in the idx=2
iteration, Ruby does not remember that a=11 in the previous iteration,
but it also does not complain about an undefined local variable "a"
(which it of course does outside the block). I haven't been able to
find this behavior mentioned in the documentation or in this
group--can you point me to something that will clarify for me what is
going on?

Thanks,
Steve

data=[1,2]
data.each do | idx|
	if idx == 1
		a = 11
		print "idx=1: a=",a,"\n"
	elsif idx == 2
		b = 12
		print "idx=2: a=",a," b=",b,"\n"
	end
end
print "after:\n"
print "a=",a," b=",b,"\n"
	
>c:\ruby\bin\ruby test.rb
idx=1: a=11
idx=2: a=nil b=12
after:
test.rb:12: undefined local variable or method `a' for main:Object
(NameError)
>Exit code: 1

4.Newbie block question

Hi folks

I'm working on some code that extracts data from a set of XML files 
using REXML stores this as arrays of arrays of floats (one array of 
floats per file), does some processing and then writes the results to 4 
text files for visualisation with gnuplot.

However, what happens is that although 4 files get created all the data 
gets saved in the first one to be opened. It's as if the block in 
writeMatrix() stores the reference to the first File object and uses 
that on the other 3 method invocations. If that's the case then I've 
obviously failed to understand the appropriate way to use a block.

What would be a better way to code this in ruby?

thanks

Dave

Here's a portion of the class handling writing the files.

class TuneInputData

   ... snip snip ...

  def writeData()

    writeMatrix(@@LUMINANCE_DATA_FILE, @imageVector)

    writeMatrix(@@VOICE_DATA_FILE, @voiceVector)

    writeMatrix(@@SOUND_DATA_FILE, @soundVector)

    writeMatrix(@@RHYTHM_DATA_FILE, @rhythmVector)

    writeColumn(@@COLOURFULNESS_DATA_FILE, @imageColourfulness)

  end

  def writeMatrix(filename, matrix)

    file = File.new(filename, "w")

    matrix.each { |row| writeRow(file, row) }

  end

  def writeRow(file, row) 

    outString = ""

    row.each { |v| outString = outString + v.to_s + " " }

    file.puts(outString)

  end

  ... snip snip ...

end



5.procs/blocks - blocks with procs, blocks with blocks?

Well, maybe not blocks with blocks but blocks with yield?  although
right now, I only have a fix for procs with blocks and not blocks with
blocks via blocks with yield when a proc block is not in stock...

class Proc
  alias __proc_block_call call
  alias __proc_block_indexer []
  
  def call(*args, &block)
    __proc_block_call(*(block.nil? ? args : args << block))
  end
  
  def [](*args, &block)
    __proc_block_indexer(*(block.nil? ? args : args << block))
  end
end

-----
usage

prc = Proc.new {|arg, proc_block|
  p arg
  proc_block[arg]
}

prc.call("Foo") {|*what|
  puts "Got #{what.length} whats -- #{what.inspect}"
}

produces:

"Foo"
Got 1 whats -- ["Foo"]


- also - it looks like the indexer function cannot take a block (parse
error) - why?

6. Small regexp question

7. small question about ruby -c

8. small array/hash question



Return to ruby

 

Who is online

Users browsing this forum: No registered users and 13 guest