how does Array#map have parameter to do something like this?
Simply put, the ampersand &
is used to "pack / unpack" a method object to a block, so the effect is more-less the same as if you passed the block.
You can "get" the block that has been passed to your method by:
def method_with_block(&foo)
# do something here
foo.call
# do something else
end
This will be similar to calling yield
and not declaring &foo
as parameter. I think binding might differ between the two approaches, but in most cases the effect is what you would expect (if I am mistaken, please correct).
Of course, the ampersand works the other way around - if a method expects a block and you have a proc object, you can simply prepend it with &
, just as you wrote. To be more precise, &
calls to_proc
method of the passed object (Rails uses this in a manner similar to described in this entry about to_proc.
I hope that this answers some of your doubts. In case there is a mistake in what I wrote, feel free to correct it.
Readings you might find useful:
- Programming Ruby, essential book
- Wikibooks contains a section about this topic
- This simple blog entry shows an example
How is array map working without passing the parameter?
Please read the map documentation.
The map
method pass 3 arguments to the provided callback: the current element, the index and the original array.
You'll find everything in the doc.
How do I get the right this in an Array.map?
Just realized I should have read the documentation for Array.map()
more carefully. One simply needs to pass in the this
value as the second parameter of map()
http://codepen.io/anon/pen/VLggpX
a = {
foo: 'bar',
things: [1, 2, 3],
showFooForEach: function() {
this.things.map(function(thing) {
console.log(this.foo, thing);
}, this);
}
}
a.showFooForEach();
In addition, understanding how bind()
, call()
and apply()
work are a must for serious JavaScript developers. These allow us to skip silly assignments like
var self = this;
myItems.map(function(item) {
self.itemArray.push(item);
});
with
myItems.map(function(item) {
this.itemArray.push(item);
}.bind(this));
Array.map want to map a value to nothing
reduce
the array using the modulo operator:
function chunk(arr, n) {
return arr.reduce(function (p, c, i) {
if (i % n === 0) p.push([]);
p[p.length - 1].push(c);
return p;
}, []);
}
chunk(arr, 2); // [[1,2],[3,4],[5,6],[7]]
DEMO
Array_map function in php with parameter
Apart from creating a mapper object, there isn't much you can do. For example:
class customMapper {
private $customMap = NULL;
public function __construct($customMap){
$this->customMap = $customMap;
}
public function map($data){
return $data[$this->customMap];
}
}
And then inside your function, instead of creating your own mapper, use the new class:
$ids = array_map(array(new customMapper('param2'), 'map'), $data['student_teacher']);
This will allow you to create a custom mapper that can return any kind of information... And you can complexify your customMapper to accept more fields or configuration easily.
How to Pass Parameter to array.map()?
You can do something called a factory currying. Effectively, you make a function that will return another function which is tailored to your needs. In this case, an anonymous one.
var arr = [1, 2, 3, 4, 5];
function multiplyBy(scale) {
return function(num){
return num * scale;
}
}
console.log( arr.map( multiplyBy(4) ));
This works because the scope of the anonymous function that is returned is within that of the factory outer function. So, whenever we produce a new function, it will retain the value of scale
that was given for its production.
Edit: The last part of @Bergi 's answer is the same as mine. The concept is apparently called currying. Thanks @Bergi ! The Factory pattern is more often applied to the production of objects, as Bergi noted, but it was the only thing I could think of at the time, and javascript sort of treats functions like objects. In this specific case, they are effectively similar. Here is a good reference for currying in JavaScript
What is the concept of Array.map?
Let's rewrite it a bit, and start working from inside out.
var mapCell = function (row) {
return columns.map(
function(column) {
return {
column : column,
value : getColumnCell(row, column)
}
}
)
}
The function(column)
part is essentially a function that takes a column as a parameter, and returns a new object with two properties:
- column, that is the original value of the parameter, and
- value, that is the result of calling the getColumnCell function on the row (external variable) and column (parameter)
The columns.map()
part calls the Array.map
function, that takes an array and a function, and runs the function for every last item of it, and returns the results. i.e. if the input is the array [1, 2, 3, 4, 5]
and the function is something like isEven
, the result will be the array [false, true, false, true, false]
. In your case, the input are the columns, and the output is a list of objects, each of which has a column and a value properties.
Lastly, the var mapCell = function (row)
part declares that the variable mapCell
will contain a function of one variable called row
- and this is the same row
that is used in the inner function.
In a single sentence, this line of code, declares a function that when run, will take a row and return values for all columns for that row.
Related Topics
Ruby: Parsing a String Representation of Nested Arrays into an Array
Ruby:Difference Between Instance and Local Variables in Ruby
Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby
How to Get Class Instances in Ruby
Ruby on Rails Console Is Hanging When Loading
Why Is Sum So Much Faster Than Inject(:+)
Rails Respond_To Format.Js API
Cron Job Not Working in Whenever Gem
"Rake Assets:Precompile" Gives Punc Error
How to Implement a Friendship Model in Rails 3 for a Social Networking Application
Best Way to Add Comments in Erb
Best Ruby on Rails Social Networking Framework
Why Can't I Install Rails on Lion Using Rvm
Ruby - Net/Http - Following Redirects
How to Set a File Upload Programmatically Using Paperclip
Using Rvm on Ubuntu 12.04 to Use Rails. the Program 'Rails' Is Currently Not Installed