def home
letter = 'A'
@markers = Location.all.to_gmaps4rails do |loc, marker|
marker.infowindow render_to_string(partial: '/locations/info',
locals: {object: loc})
marker.picture({picture: "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=#{letter.next!}|9966FF|000000",
width: 32,
height: 32,
shadow_picture: "http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
shadow_width: 110,
shadow_height: 110,
shadow_anchor: [17,36]})
marker.title "Title - #{loc.name}"
marker.sidebar render_to_string(partial: '/locations/sidebar',
locals: {object: loc})
marker.json({id: loc.id})
end
end
Cool stuff. So this works. It cycles through the do loop
and increments the letter. Problem is, it starts at B. I tried using just letter
in the picture, then at the end using letter.next!
, and even letter = letter.next
, but gmaps throws an error at me.
Is there a way to assign something besides 'A' to letter
?
Simple, direct solution. function nextChar(c) { return String. fromCharCode(c. charCodeAt(0) + 1); } nextChar('a');
Approach: Use charCodeAt() method to return the Unicode of the character at the specified index in a string. Increment/Decrement the ASCII value depending on the requirement. Use fromCharCode() method to convert Unicode values into characters.
JavaScript has an even more succinct syntax to increment a number by 1. The increment operator ( ++ ) increments its operand by 1 ; that is, it adds 1 to the existing value. There's a corresponding decrement operator ( -- ) that decrements a variable's value by 1 .
You could also make use of PHP's range() function: $chars = range('a', 'z'); // ['a', 'b', 'c', 'd', ...] Save this answer.
What about this?
letters = ('A'..'Z').to_a
letters.shift #=> 'A'
letters.shift #=> 'B'
This works, but I'll second @patrick-oscity: this is obscure code that hardly reveals its intention.
letter = '@'
letter.next! #=> "A"
Check '@ABCD'.codepoints.to_a
to see why it works.
Well technically, '@'
is the predecessor of 'A'
, because the ASCII value of '@'
is 64 and the value of 'A'
is 65. Observe:
'A'.codepoints.first
#=> 65
'A'.codepoints.first - 1
#=> 64
('A'.codepoints.first - 1).chr
#=> "@"
('A'.codepoints.first - 1).chr.next
#=> "A"
in that sense:
'@'.next == 'A'
#=> true
but i strongly discourage the use of black magic™. Use something like @nicooga's approach in real code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With