# Need explanation for this

**URL:** <https://www.ruby-forum.com/t/need-explanation-for-this/143409>\
**Category:** Rails\
**Created:** [July 18, 2008, 7:08am UTC](https://www.ruby-forum.com/t/need-explanation-for-this/143409 "2008-07-18T07:08:43Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![lostwarrior](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/a88e57/32.png) [@lostwarrior](https://www.ruby-forum.com/u/lostwarrior)\
**Post date:** [July 18, 2008, 7:08am UTC](https://www.ruby-forum.com/t/need-explanation-for-this/143409/1 "2008-07-18T07:08:43Z")

</div>

hi please gice explanation for this

1: def json\_attributes\_for(model, \*attrs)  
2: attrs = [attrs].flatten.map(&:to\_s)  
3: model.attributes.delete\_if{|k,v| !attrs.include?(k) }.to\_json  
4: end

---

<div class="post-metadata">

**Author:** ![lostwarrior](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/a88e57/32.png) [@lostwarrior](https://www.ruby-forum.com/u/lostwarrior)\
**Post date:** [July 18, 2008, 8:32am UTC](https://www.ruby-forum.com/t/need-explanation-for-this/143409/2 "2008-07-18T08:32:26Z")

</div>

On Jul 18, 6:08 am, Lost W. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> hi please gice explanation for this
> 
> 1: def json\_attributes\_for(model, \*attrs)  
> 2: attrs = [attrs].flatten.map(&:to\_s)  
> 3: model.attributes.delete\_if{|k,v| !attrs.include?(k) }.to\_json  
> 4: end

It returns a json hash for the object, but only including the  
specified attributes. It’s rewriting the wheel though, first of hashes  
have a slice method so that messing around with delete\_if is not  
needed, and secondly to\_json takes a :only option.

Fred
